Last active
July 29, 2024 13:11
-
-
Save Blacksmoke16/53d27ff133a9607fe6c75b5a5e0ddde8 to your computer and use it in GitHub Desktop.
Test Crinja + Athena integration
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "crinja" | |
ADI.configuration_annotation Blog::Annotations::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 | |
ATH.configure({ | |
framework: { | |
format_listener: { | |
enabled: true, | |
rules: [ | |
{path: /^\//, priorities: ["json", "html"]}, | |
], | |
}, | |
}, | |
}) | |
@[Crinja::Attributes] | |
class User | |
include JSON::Serializable | |
include Crinja::Object::Auto | |
getter name : String | |
def initialize(@name : String); end | |
end | |
class HelloController < ATH::Controller | |
@[Blog::Annotations::Template("hello.crinja.html")] | |
@[ARTA::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