gpt4 book ai didi

ruby-on-rails - 渲染与部分渲染和良率之间的差异

转载 作者:行者123 更新时间:2023-12-03 06:04:21 25 4
gpt4 key购买 nike

我已经从 Rails 指南中读到了它,已经看过 Micheal Hartel 的书,现在又从 Rails View 的书中读到了它,但我仍然感到困惑:(

有一个_footer.html.erb文件,因此它是一个“部分”,并且在它编写的代码中:

<%=render 'layouts/footer' %>

所以我的理解是,当它看到这个时,就会在此处插入页脚文件的 HTML。好的...几页后,它说:

<%= render partial: 'activitiy_items/recent' %>

那么为什么这次我们有“部分”这个词,而上一次却没有呢?

我在其他地方看到<%= yield :sidebar %>

所以这个yield还在其位置插入 HTML 吗?好吧,这不是render正在做?

我希望如果另一个程序员而不是书籍向我解释这一点,也许这次我明白了:)

最佳答案

渲染 & 渲染部分:

  • render 'some_view'renderpartial: 'some_view' 的简写。

  • render file: 'view' 将查找文件 view.html.erb 而不是 _view.html.erb (.erb 或您使用的任何其他渲染器)

  • render 如果您不使用集合或布局,则可以传递局部变量,例如

     render 'some/path/to/my/partial', custom_var: 'Hello'

产量 & content_for

  • yield 通常用于布局。它告诉 Rails 将此 block 的内容放在布局中的那个位置。
  • 当您执行与 content_for :something 关联的 yield :something 时,您可以传递一个代码块( View )来显示 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>
<小时/>

可能有帮助的帖子:

文档和指南的链接:

关于ruby-on-rails - 渲染与部分渲染和良率之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16822775/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com