From 21b194a901acf033ee3425a39fe1906fc1416693 Mon Sep 17 00:00:00 2001 From: Sdogruyol Date: Sat, 9 Jul 2016 19:54:35 +0300 Subject: [PATCH] Add content_for and yield_content helpers <3. Thanks @RX14 --- spec/asset/hello_with_content_for.ecr | 5 ++--- spec/view_spec.cr | 7 ++++--- src/kemal/helpers.cr | 28 +++++++++++---------------- 3 files changed, 17 insertions(+), 23 deletions(-) diff --git a/spec/asset/hello_with_content_for.ecr b/spec/asset/hello_with_content_for.ecr index cc3beba..149b294 100644 --- a/spec/asset/hello_with_content_for.ecr +++ b/spec/asset/hello_with_content_for.ecr @@ -1,6 +1,5 @@ Hello <%= name %> -<% content_for "custom" do |io| %> - io << "

Hello from otherside

" - io +<% content_for "custom" do %> +

Hello from otherside

<% end %> \ No newline at end of file diff --git a/spec/view_spec.cr b/spec/view_spec.cr index 1821c60..1d6a6fe 100644 --- a/spec/view_spec.cr +++ b/spec/view_spec.cr @@ -36,12 +36,13 @@ describe "Views" do end it "renders layout with content_for" do - get "/view" do - name = "Kemal" + 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") + 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 48863b9..b1491f8 100644 --- a/src/kemal/helpers.cr +++ b/src/kemal/helpers.cr @@ -1,16 +1,18 @@ require "kilt" -CONTENTS = {} of String => MemoryIO -> String +CONTENT_FOR_BLOCKS = Hash(String, Proc(String)).new -def content_for(name : String, &block : MemoryIO -> String) - puts "Called content_for" - CONTENTS[name] = block - # CONTENTS[name] = block +macro content_for(key) + CONTENT_FOR_BLOCKS[{{key}}] = ->() { + __kilt_io__ = MemoryIO.new + {{ yield }} + __kilt_io__.to_s + } + nil end -def yield_content(name) - puts "Called yield_content" - CONTENTS[name].call +macro yield_content(key) + CONTENT_FOR_BLOCKS[{{key}}].call end # Uses built-in ECR to render views. @@ -20,12 +22,7 @@ end # end macro render(filename, layout) content = render {{filename}} - if CONTENTS.size > 0 - puts "CONTENTS greater than 0" - render {{layout}} - else - render {{layout}} - end + render {{layout}} end macro render(filename, *args) @@ -38,9 +35,6 @@ macro return_with(env, status_code = 200, response = "") next end - - - # Adds given HTTP::Handler+ to handlers. def add_handler(handler) Kemal.config.add_handler handler