chr*_*ina 13 ruby ruby-on-rails ruby-on-rails-3
有人可以解释" <%= render %>"和" <%= yield %>与<% content_for :partial do %>/ <% end %>" 之间的区别吗?具体来说,当从一个切换到另一个时,路由如何变化,使用一个优于另一个的优点,何时使用一个优于另一个.这是我发现的最接近的解释,但对我来说还不够清楚.
我已经尝试了几天来绕过这个,但似乎我尝试的每个配置都接近或出错.
如果那里有三个观点,aaa与bbb和ccc,各有一个index.html.erb,但bbb并ccc有_content.html.erb部分(由下划线表示)你怎么能完成获取bbb或ccc部分在aaa使用两种render或yield?
以下作品:
aaa的index.html.erb:
<div">
<%= render 'bbb/content' %>
</div>
Run Code Online (Sandbox Code Playgroud)
和bbbs _content.html/erb:
<p>Content from bbb.</p>
Run Code Online (Sandbox Code Playgroud)
但这不是:
aaa的index.html.erb:
<div">
<%= yield :container %>
</div>
Run Code Online (Sandbox Code Playgroud)
和bbbs _content.html/erb:
<% content_for :container do %>
<p>Content from bbb.</p> ### viewed in aaa
<% end>
Run Code Online (Sandbox Code Playgroud)
并且cccs _content.html.erb什么都没有,或者content_for,但是我仍然没有得到aaaindex.html来填充内容.
如果我使用渲染,我可以明确地放置内容.但我认为使用它的好处yield :whatever将允许我选择填充它的内容,并且我不能让它在我更改它时立即填充任何内容从渲染到产量.我是否还必须更新路线文件?如果是这样,我该如何选择填充哪一个?这是否意味着它在控制器中?并需要一个行动?
我也有,但它取决于最初路由到哪个文件,但就像我说的,我想我需要先了解两者之间的差异才能开始使用部分文件.
首先,产量是红宝石,渲染是铁轨.通常,对于内部内容根据操作/上下文而变化的应用程序,使用公共布局.问题通常在于定义布局结束的位置以及特定于上下文的模板的开始.举个例子,HTML标题标签.假设您有一个名为Cities的应用程序.在大多数情况下,您希望页面标题始终为"城市".但是,如果您是在阿姆斯特丹页面内,那么您希望将"阿姆斯特丹"作为您的页面标题.
# application.html.erb
<html>
<head>
<%= content_for?(:page_title) ? yield(:page_title) : "Cities" %>
......
# city/index.html.erb
<% content_for :page_title do %>
<%= @city.name %>
<% end %>
<div class="bla"...
Run Code Online (Sandbox Code Playgroud)
在Rails中,您通常会在应用程序布局中定义应用程序标题.更改页面标题的一种策略是在特定城市模板中使用content_for并相应地进行更改.
另一方面,渲染完成不同的渲染策略.直行.当您调用render时,它会呈现.content_for/yield不会自动呈现,它存储在某处,然后填充到位的丢失点.因此,与渲染相比,您可以将其视为"存储/搜索/替换",而渲染只是简单渲染.
使用一个优于另一个的经验法则是:如果您编写的模板需要在每个上下文中显示不同的信息,请强烈考虑使用content_for.
yieldRuby 代码(Proc 类)并获取您的块并执行它应该做的事情。与其他基于 Ruby 的做同样事情的方式相比,Yield 也很快。我假设(而且我只)在布局中使用它,因为它很快,而且我会漫不经心地做在 Rails 中正常的事情。yield还用于将内容传递到布局中的特定位置。我经常<%= yield :head %>在头部,就在头部标签上方,这样我就可以传递有时出现的随机怪异。
render您将参数传递给的 Rails 代码,正如文档所说,“呈现将作为响应正文返回到浏览器的内容”。部分,动作,文本,文件...等。
在视图和控制器中使用。
When your controller method exits, it renders the associated file. So the edit controller renders edit.html.erb. It uses the specified layout or application.html.erb if none is specified.
Within your layout file, when you call yield it will fill in the information from your render. If you call yield with a parameter, it will look for a content_for section in your render file matching that parameter. I'm not completely sure, but I don't think you can call yield from outside of your layout file, and I don't think it will fill in any information except that found in your render file.
Anywhere in your layout file or your rendered file, you can render a partial by calling render with the partial name minus the underscore.
I hope that helps.
Edit to answer question in comment:
yield并render执行类似的功能,但yield仅在渲染文件中查找,同时render指定要渲染的文件。另外,render输出整个文件,但yield使用参数可以仅输出文件的一小部分。
| 归档时间: |
|
| 查看次数: |
14252 次 |
| 最近记录: |