diff --git a/spec/asset/hello_with_content_for.ecr b/spec/asset/hello_with_content_for.ecr new file mode 100644 index 0000000..149b294 --- /dev/null +++ b/spec/asset/hello_with_content_for.ecr @@ -0,0 +1,5 @@ +Hello <%= name %> + +<% content_for "custom" do %> +

Hello from otherside

+<% end %> \ No newline at end of file diff --git a/spec/asset/layout_with_yield.ecr b/spec/asset/layout_with_yield.ecr new file mode 100644 index 0000000..035cc8d --- /dev/null +++ b/spec/asset/layout_with_yield.ecr @@ -0,0 +1,3 @@ +<%= content %> + +<%= yield_content "custom" %> \ No newline at end of file diff --git a/spec/view_spec.cr b/spec/view_spec.cr index ab17b60..1d6a6fe 100644 --- a/spec/view_spec.cr +++ b/spec/view_spec.cr @@ -34,4 +34,15 @@ describe "Views" do client_response = call_request_on_app(request) client_response.body.should contain("Hello world") end + + it "renders layout with content_for" do + get "/view/:name" do |env| + name = env.params.url["name"] + render "spec/asset/hello_with_content_for.ecr", "spec/asset/layout_with_yield.ecr" + end + request = HTTP::Request.new("GET", "/view/world") + client_response = call_request_on_app(request) + client_response.body.should contain("Hello world") + client_response.body.should contain("

Hello from otherside

") + end end diff --git a/src/kemal/helpers.cr b/src/kemal/helpers.cr index bf6f4c6..b1491f8 100644 --- a/src/kemal/helpers.cr +++ b/src/kemal/helpers.cr @@ -1,5 +1,20 @@ require "kilt" +CONTENT_FOR_BLOCKS = Hash(String, Proc(String)).new + +macro content_for(key) + CONTENT_FOR_BLOCKS[{{key}}] = ->() { + __kilt_io__ = MemoryIO.new + {{ yield }} + __kilt_io__.to_s + } + nil +end + +macro yield_content(key) + CONTENT_FOR_BLOCKS[{{key}}].call +end + # Uses built-in ECR to render views. # # Usage # get '/' do