我读 http://www.padrinorb.com/guides/application-helpers 但是我尚不清楚每个视图助手的用例是什么。特别是如何 content_for/yield_content, render/partial, capture_html, and concat_content 全都在一起吗?

现在我一直在使用 render 'my/view' 在我的控制器中扔一些 =partial 'my/partial''my/view' 只是将主模板文件分解为较小的块。

正确的方法是正确的吗?我何时/在哪里使用其他助手功能?

有帮助吗?

解决方案

让我们浏览用例。

  1. content_for/farts_content

这是为了将内容注入可能有用的布局文件。示例是将其他CSS/脚本添加到另一个模板的布局中。指南上的示例是相同的,显示了如何从需要它们的任何模板中将CSS文件添加到布局中。您还可以将其用于侧栏,其他链接等上的内容。它是针对不需要自己的模板但需要根据所显示的视图将信息传递回布局的事物。

  1. 渲染/部分

渲染是用于显示与路由关联的给定模板。处理路线后,渲染应用于主要操作。在视图中,部分就像是“方法”。它可以重复使用,可以传递变量以更改输出。您使用主模板中的部分来分解代码和重复使用否则似乎多余的视图。

  1. capture_html/concat_content

这通常用于创建自己的助手,以占据内容。例如,让我们创建一个带有HAML块并将其包裹在DIV中的助手。用法如下:

# template.haml
# NOTE the equals so the content is returned 
# and added to the view directly
= div_wrapper do 
  %h1 Some heading
  %p This is now wrapped in a div

要实现它并在模板中使用它,您需要能够“捕获” HAML传递到块中,以便处理然后围绕它包裹DIV。这就是Capture_html的位置:

def div_wrapper(&block)
   nested_content = capture_html(&block)
   content_tag(:div, nested_content)
end

这将使内容吐出在Div中包裹的视图中。现在,让我们假设我们希望这个助手变得更加复杂,因此您希望用途更像:

# template.haml
# NOTE the dash so the content is not outputted directly
- div_wrapper do 
  %h1 Some heading
  %p This is now wrapped in a div

但这也适用于其他帮助者:

# some_helper.rb
def example(name)
  div_wrapper { "<h1>Test</h1>" }
end

为了在模板和笔直的Ruby中正确打印从助手的包装内容,我们可以使用Concat_Content并检查是否需要将结果“ concat”到模板上或简单地返回。

 def div_wrapper(&block)
   nested_content = capture_html(&block)
   tag_result = content_tag(:div, nested_content)
   block_is_template?(block) ? concat_content(tag_result) : tag_result
end

我希望这是基本概述。功能可以重叠,但通常很清楚什么时候使用基于特定上下文的使用。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top