Rails布局使用控制器条件进行渲染(Rails Layout Rendering with controller condition)

编程入门 行业动态 更新时间:2024-10-27 03:28:01
Rails布局使用控制器条件进行渲染(Rails Layout Rendering with controller condition)

我不知道这样做的最佳方法是什么。

在我的application.html.erb上我定义了一个标题div。

我的默认控制器(root)是主页控制器。 我希望如果我在主页的索引处标题是使用某些内容呈现的,但所有其他控制器都会在该标题内呈现另一个内容。

如何在该标题div中创建一个条件,以根据正在呈现的控制器呈现不同的内容?

I don't know what's the best way to doing this.

On my application.html.erb I define a header div.

My default controller ( root ) is a homepage controller. And I wish that if I'm at index of the homepage the header is rendering with some content, but all other controllers render another content inside that header.

How can I make a condition in that header div to render different content based on the controller that's being rendered?

最满意答案

您可以使用content_for帮助程序在从应用程序布局中生成的各个视图模板中定义标记块。

application.html.erb

<div id="header"> <%= yield :header %> </div>

然后在控制器的视图模板中的任何位置包含这样的代码:

<% content_for :header do %> This is a controller-specific header. <% end %>

请注意,您可以根据需要定义任意数量的块,因此您也可以使用条件侧边栏等。

Layouts和content_for Railscast

You can use the content_for helper to define a block of markup in individual view templates that's yielded to from the application layout.

application.html.erb:

<div id="header"> <%= yield :header %> </div>

Then include code like this anywhere within a controller's view template:

<% content_for :header do %> This is a controller-specific header. <% end %>

Note that you can define as many of these blocks as you like, so you could have a conditional sidebar etc. as well.

Layouts and content_for Railscast

更多推荐

本文发布于:2023-08-05 18:25:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1436694.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:控制器   布局   条件   Rails   condition

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!