将变量从视图传递到布局的部分视图
我正在尝试使用局部变量来呈现应用程序的菜单,使用 CSS 将“选项卡”大写,基于局部变量(选项卡):
<%= link_to "employees", jobs_path, :class => (tab=="employees" ? "selected":"unselected") %>
<a class="unselected">jobs</a>
<%= link_to "tags", tags_path, :class => (tab=="tags" ? "selected":"unselected") %>
局部变量嵌入在应用程序的布局中:
<body>
...
<!-- tab variable needs to be set in the view, not the layout -->
<%= render :partial => "layouts/primary_menu", :locals => { :tab => "profiles" } %>
...
</body>
不幸的是,我需要在查看,但该变量不可用。我应该使用 :content_for 符号而不是 :locals 吗?
在某些时候,我可能想将模型实例变量传递给部分,因此解决方案需要灵活。
有更好的方法吗?
I am trying using a partial to render the application's menu, capitalizing the 'tab' using CSS, based on a local variable (tab):
<%= link_to "employees", jobs_path, :class => (tab=="employees" ? "selected":"unselected") %>
<a class="unselected">jobs</a>
<%= link_to "tags", tags_path, :class => (tab=="tags" ? "selected":"unselected") %>
The partial is embedded in the the Application's layout:
<body>
...
<!-- tab variable needs to be set in the view, not the layout -->
<%= render :partial => "layouts/primary_menu", :locals => { :tab => "profiles" } %>
...
</body>
Unfortunately, I need to set the variable's value in the view, but the variable isn't available. Should I be using the :content_for symbol instead of :locals?
At some point, I may want to pass a model instance variable to the partial, so the solution needs to be flexible.
Is there a better approach?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为有多种方法可以处理这个问题,这里有一个 - 不一定是最好的
另一种方法 - 使用成员变量而不是本地变量(这有点像作弊 - 但有效)
访问 @current_tab
现在直接在 Primary_menu 部分使用 content_for
http://guides.rubyonrails.org/layouts_and_rendering.html#understand-yield
I think there are multiple ways to handle this, here is one - not necessarily the best
another way - use a member variable instead of locals (this is kinda like cheating - but effective)
now access the @current_tab directly in the primary_menu partial
Using content_for
http://guides.rubyonrails.org/layouts_and_rendering.html#understanding-yield
我决定使用 link_to_unless_current UrlHelper:
I decided to make use of the link_to_unless_current UrlHelper: