Fix content rendering

This commit is contained in:
matthewmcgarvey 2022-02-23 17:36:28 -06:00 committed by Serdar Dogruyol - Sedo セド
parent 59720fbd16
commit d6dc893052
2 changed files with 19 additions and 13 deletions

View file

@ -22,7 +22,7 @@ describe "Views" do
end end
request = HTTP::Request.new("GET", "/view/world") 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("Hello world") client_response.body.strip.should eq("<html>Hello world\n</html>")
end end
it "renders layout" do it "renders layout" do
@ -59,4 +59,14 @@ describe "Views" do
client_response.body.should contain("Hello world") client_response.body.should contain("Hello world")
client_response.body.should contain("<h1>Hello from otherside</h1>") client_response.body.should contain("<h1>Hello from otherside</h1>")
end end
it "does not render content_for that was not yielded" do
get "/view/:name" do |env|
name = env.params.url["name"]
render "#{__DIR__}/asset/hello_with_content_for.ecr", "#{__DIR__}/asset/layout.ecr"
end
request = HTTP::Request.new("GET", "/view/world")
client_response = call_request_on_app(request)
client_response.body.should_not contain("<h1>Hello from otherside</h1>")
end
end end

View file

@ -1,4 +1,4 @@
CONTENT_FOR_BLOCKS = Hash(String, Tuple(String, Proc(String))).new CONTENT_FOR_BLOCKS = Hash(String, Tuple(String, Proc(Nil))).new
# `content_for` is a set of helpers that allows you to capture # `content_for` is a set of helpers that allows you to capture
# blocks inside views to be rendered later during the request. The most # blocks inside views to be rendered later during the request. The most
@ -34,13 +34,7 @@ CONTENT_FOR_BLOCKS = Hash(String, Tuple(String, Proc(String))).new
# layout, inside the <head> tag, and each view can call `content_for` # layout, inside the <head> tag, and each view can call `content_for`
# setting the appropriate set of tags that should be added to the layout. # setting the appropriate set of tags that should be added to the layout.
macro content_for(key, file = __FILE__) macro content_for(key, file = __FILE__)
%proc = ->() { CONTENT_FOR_BLOCKS[{{key}}] = Tuple.new {{file}}, ->() { {{ yield }} }
__view_io__ = IO::Memory.new
{{ yield }}
__view_io__.to_s
}
CONTENT_FOR_BLOCKS[{{key}}] = Tuple.new {{file}}, %proc
nil nil
end end
@ -60,10 +54,12 @@ end
# ``` # ```
macro render(filename, layout) macro render(filename, layout)
__content_filename__ = {{filename}} __content_filename__ = {{filename}}
io = IO::Memory.new content_io = IO::Memory.new
content = ECR.embed {{filename}}, io ECR.embed {{filename}}, content_io
ECR.embed {{layout}}, io content = content_io.to_s
io.to_s layout_io = IO::Memory.new
ECR.embed {{layout}}, layout_io
layout_io.to_s
end end
# Render view with the given filename. # Render view with the given filename.