我从Rails指南上读过它,看过Micheal的书,现在又从Rails View书中读到它,但我仍然感到困惑:(
有一个_footer.html.erb文件,所以它是一个“局部”文件,并且在它编写的代码中:
<%=render 'layouts/footer' %>所以我的理解是,当它看到这一点时,就会在这里插入页脚文件的HTML。好的..。现在几页后,它是这样说的:
<%= render partial: 'activitiy_items/recent' %>那么为什么这一次我们在这里有"partial“这个词,而上一次我们没有呢?
在其他地方我看到了<%= yield :sidebar %>
所以这个yield也会插入超文本标记语言吗?这不就是render正在做的吗?
我希望如果另一位程序员而不是书本向我解释这一点,也许这次我能理解:)
发布于 2013-05-30 04:07:53
render和render partial:
render 'some_view'是render partial: 'some_view'.render file: 'view'将查找文件view.html.erb而不是_view.html.erb的简写(您use)render的.erb或任何其他渲染器不会接受附加局部变量,为此需要使用render partial:,如下所示):呈现部分:'some/path/to/my/partial',本地变量:{ custom_var:'Hello‘}
(http://guides.rubyonrails.org/layouts_and_rendering.html#passing-local-variables)
yield和content_for
yield通常用在layouts中。它告诉Rails将此块的内容放在布局中的那个位置。content_for :something关联的视图时,可以传递一段代码( yield :something )来显示放置视图的位置(请参阅下面的示例)。一个关于产量的小例子:
在您的布局中:
<html>
<head>
<%= yield :html_head %>
</head>
<body>
<div id="sidebar">
<%= yield :sidebar %>
</div>
</body>在您的一个视图中:
<% content_for :sidebar do %>
This content will show up in the sidebar section
<% end %>
<% content_for :html_head do %>
<script type="text/javascript">
console.log("Hello World!");
</script>
<% end %>这将生成以下HTML:
<html>
<head>
<script type="text/javascript">
console.log("Hello World!");
</script>
</head>
<body>
<div id="sidebar">
This content will show up in the sidebar section
</div>
</body>可能对有帮助的帖子
指向文档和指南的链接
发布于 2013-06-13 17:24:41
关于render、render :partial和yield
中的两个文件
render :模板主要是根据具有语法demo.html.erb的操作创建的
render :partial是可重用的,可以从不同的视图调用,在应用程序中的许多页面之间共享,语法是_demo.html.erb的
Yield是一种使用输出调用代码块的方法,但render将包含调用它的部分页面模板。在rails中,their主要用于布局,而render则用于操作或其模板
https://stackoverflow.com/questions/16822775
复制相似问题