从另一个视图渲染一个视图
我有几个视图希望出现在渲染的每个视图上,但如果没有重复代码或违反规范,我似乎找不到实现此目的的方法。
这是我当前的代码,在每个视图中进行调用:
def ImOnABoat::Views def layout html do head do title "Petstore" end body do yield end end end def navigation p "Welcome to our tiny petstore!" end def poodle navigation # Have to duplicate this in every view p "We have a poodle!" end def fluffy_bunny navigation # Have to duplicate this in every view p "Come see-- OH CRAP IT'S A VELOCIRAPTOR!" end end
我还可以通过允许公共块在主体之外渲染来使其工作,但这违反了规范,并且最终可能会严重破坏一些抓取脚本。
def layout def head do title "Petstore" end nav # This is not inside <body>! def body do yield end end
I have a couple of views I'd like to have appear on every view that is rendered, but short of duplicating code or breaking the specifications, I can't seem to find a way to accomplish this.
Here's my current code, putting calls in every view:
def ImOnABoat::Views def layout html do head do title "Petstore" end body do yield end end end def navigation p "Welcome to our tiny petstore!" end def poodle navigation # Have to duplicate this in every view p "We have a poodle!" end def fluffy_bunny navigation # Have to duplicate this in every view p "Come see-- OH CRAP IT'S A VELOCIRAPTOR!" end end
I can also make it work by allowing the common blocks to render outside the body, but this is against specification and will probably end up horribly breaking some scraper scripts down the road.
def layout def head do title "Petstore" end nav # This is not inside <body>! def body do yield end end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这可以使用 Rails 布局并在布局中渲染部分来完成。减少这种“建设”的需要并使管理变得更加容易。
http://guides.rubyonrails.org/layouts_and_rendering.html#using-partials
This could be accomplished using rails layouts and rendering partials in the layout. Reducing the need for such 'building' and making management easier.
http://guides.rubyonrails.org/layouts_and_rendering.html#using-partials
请记住,这是纯 Ruby,因此您只需在布局中调用
navigation
方法即可:Remember that this is plain Ruby, so you can simply call the
navigation
method in the layout: