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 %>
<% content_for "custom" do |io| %>
io << "<h1> Hello from otherside </h1>"
io
<% content_for "custom" do %>
<h1>Hello from otherside</h1>
<% end %>

View File

@ -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("<html>Hello world")
client_response.body.should contain("<h1>Hello from otherside</h1>")
end
end

View File

@ -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