从另一个视图呈现视图
问题描述:
我有几个视图我希望在呈现的每个视图上都显示,但缺少重复代码或违反规范,我似乎无法找到一种方法来完成这个。从另一个视图呈现视图
这里是我当前的代码,将调用每个视图:
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
答
请记住,这是普通的红宝石,所以你可以简单地调用在布局中navigation
方法:
module ImOnABoat::Views
def layout
html do
head { title "Petstore" }
body do
navigation
yield
end
end
end
def navigation
p "Welcome to our tiny petstore!"
end
def poodle
p "We have a poodle!"
end
def fluffy_bunny
p "Come see-- OH CRAP IT'S A VELOCIRAPTOR!"
end
end
答
这可以通过在布局中使用导轨布局和渲染部分来实现。减少对这种“建筑”的需求并简化管理。
http://guides.rubyonrails.org/layouts_and_rendering.html#using-partials