如何在Ruby和ERB(而非Rails)中使用视图和布局? [英] How can I use views and layouts with Ruby and ERB (not Rails)?
问题描述
如何在Ruby和ERB(不是Rails)中使用视图和布局?
How can I use views and layouts with Ruby and ERB (not Rails)?
今天我正在使用此代码来呈现视图:
Today i'm using this code to render my view:
def render(template_path, context = self)
template = File.read(template_path)
ERB.new(template).result(context.get_binding)
end
这很好,但是如何我实现了相同的功能,但是要在布局内渲染模板?我想调用render_with_layout(template_path,context = self),以便它具有默认布局。
This works very well, but how can I implement the same function, but to render the template inside a layout? I want to call render_with_layout(template_path, context = self), and so that it will have a default layout.
推荐答案
感谢所有答案!
我终于解决了通过这样做,我希望其他人也可以找到此代码有用:
I solved it finally by doing this, I hope someone else also can find this code useful:
def render_with_layout(template_path, context = self)
template = File.read(template_path)
render_layout do
ERB.new(template).result(context.get_binding)
end
end
def render_layout
layout = File.read('views/layouts/app.html.erb')
ERB.new(layout).result(binding)
end
我这样称呼它:
def index
@books = Book.all
body = render_with_layout('views/books/index.html.erb')
[200, {}, [body]]
end
然后它将使用硬编码(到目前为止)布局呈现我的视图..
Then it will render my view, with the hardcoded (so far) layout..
这篇关于如何在Ruby和ERB(而非Rails)中使用视图和布局?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!