Using Kemal CSRF handler with Crinja

2018 05 19 No Comments

I assume that you are using kemal, kemal-session and kemal-csrf. Require them and use add_handler to handle requests.

Default input name is authenticity_token so I used it.

require "kemal"
require "kemal-session"
require "kemal-csrf"

add_handler CSRF.new(
  allowed_methods: ["GET", "HEAD", "OPTIONS", "TRACE"],
  error: ->myerrorhandler(HTTP::Server::Context)
)

def myerrorhandler(env)
  if env.request.headers["Content-Type"]? == "application/json"
    {"error" => "csrf error"}.to_json
  else
    "No token!"
  end
end

Kemal.run

Create a function to use it in templates
(more…)

Markdown render in template side with Crinja – Crystal

2018 05 18 No Comments

Hello
In crystal ecr templates, we can use render markdown like this: <%= Markdown.to_html("# text") %>

But with crinja we cant do it as I see.

So I created template function.

require "markdown"

c = Crinja.new
c.loader = Crinja::Loader::FileSystemLoader.new("src/views/")

c.functions << Crinja.function({:str => ""}, :Markdown) do
  Markdown.to_html(arguments[:str].to_s)
end

To use it:

{{ Markdown("# title")  | safe}}

Enjoy.