Add content_for and yield_content helpers <3. Thanks @RX14

This commit is contained in:
Sdogruyol 2016-07-09 19:54:35 +03:00
parent 73d6123f3d
commit 21b194a901
3 changed files with 17 additions and 23 deletions

View file

@ -1,6 +1,5 @@
Hello <%= name %> Hello <%= name %>
<% content_for "custom" do |io| %> <% content_for "custom" do %>
io << "<h1> Hello from otherside </h1>" <h1>Hello from otherside</h1>
io
<% end %> <% end %>

View file

@ -36,12 +36,13 @@ describe "Views" do
end end
it "renders layout with content_for" do it "renders layout with content_for" do
get "/view" do get "/view/:name" do |env|
name = "Kemal" name = env.params.url["name"]
render "spec/asset/hello_with_content_for.ecr", "spec/asset/layout_with_yield.ecr" render "spec/asset/hello_with_content_for.ecr", "spec/asset/layout_with_yield.ecr"
end end
request = HTTP::Request.new("GET", "/view") request = HTTP::Request.new("GET", "/view/world")
client_response = call_request_on_app(request) client_response = call_request_on_app(request)
client_response.body.should contain("<html>Hello world") client_response.body.should contain("<html>Hello world")
client_response.body.should contain("<h1>Hello from otherside</h1>")
end end
end end

View file

@ -1,16 +1,18 @@
require "kilt" require "kilt"
CONTENTS = {} of String => MemoryIO -> String CONTENT_FOR_BLOCKS = Hash(String, Proc(String)).new
def content_for(name : String, &block : MemoryIO -> String) macro content_for(key)
puts "Called content_for" CONTENT_FOR_BLOCKS[{{key}}] = ->() {
CONTENTS[name] = block __kilt_io__ = MemoryIO.new
# CONTENTS[name] = block {{ yield }}
__kilt_io__.to_s
}
nil
end end
def yield_content(name) macro yield_content(key)
puts "Called yield_content" CONTENT_FOR_BLOCKS[{{key}}].call
CONTENTS[name].call
end end
# Uses built-in ECR to render views. # Uses built-in ECR to render views.
@ -20,12 +22,7 @@ end
# end # end
macro render(filename, layout) macro render(filename, layout)
content = render {{filename}} content = render {{filename}}
if CONTENTS.size > 0 render {{layout}}
puts "CONTENTS greater than 0"
render {{layout}}
else
render {{layout}}
end
end end
macro render(filename, *args) macro render(filename, *args)
@ -38,9 +35,6 @@ macro return_with(env, status_code = 200, response = "")
next next
end end
# Adds given HTTP::Handler+ to handlers. # Adds given HTTP::Handler+ to handlers.
def add_handler(handler) def add_handler(handler)
Kemal.config.add_handler handler Kemal.config.add_handler handler