Skip to content

Instantly share code, notes, and snippets.

@Blacksmoke16
Last active January 4, 2024 01:09
Show Gist options
  • Save Blacksmoke16/53d27ff133a9607fe6c75b5a5e0ddde8 to your computer and use it in GitHub Desktop.
Save Blacksmoke16/53d27ff133a9607fe6c75b5a5e0ddde8 to your computer and use it in GitHub Desktop.
Test Crinja + Athena integration
require "crinja"
ACF.configuration_annotation Template, name : String
@[ADI::Register]
class HTMLFormatHandler
include Athena::Framework::View::FormatHandlerInterface
private CRINJA = Crinja.new loader: Crinja::Loader::FileSystemLoader.new "#{__DIR__}/../views"
def call(view_handler : ATH::View::ViewHandlerInterface, view : ATH::ViewBase, request : ATH::Request, format : String) : ATH::Response
ann_configs = request.action.annotation_configurations
unless template_ann = ann_configs[Blog::Annotations::Template]?
raise "Unable to determine the template for the '#{request.attributes.get "_route"}' route."
end
unless (data = view.data).is_a? Crinja::Object
raise "Cannot convert value of type '#{view.data.class}' to '#{format}'."
end
content = CRINJA.get_template(template_ann.name).render({data: view.data})
ATH::Response.new content, headers: HTTP::Headers{"content-type" => "text/html"}
end
def format : String
"html"
end
end
def ATH::Config::ContentNegotiation.configure
new [
ATH::Config::ContentNegotiation::Rule.new(/^\//, priorities: ["json", "html"]),
]
end
@[Crinja::Attributes]
class User
include JSON::Serializable
include Crinja::Object::Auto
getter name : String
def initialize(@name : String); end
end
class HelloController < ATH::Controller
@[Template("hello.crinja.html")]
@[ATHA::Get("/:name")]
def say_hello(name : String) : User
User.new name
end
end
# hello.crinja.html
# <h1>
# Hello, {{ data.name }}!
# </h1>
ATH.run
# GET /John Accept: application/json # => {name: "John"}
# GET /John Accept: text/html # => <h1>Hello, John!</h1>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment