跳至内容 跳至搜索

Action View 渲染帮助器

实现允许从视图上下文渲染的方法。要使用此模块,您需要做的就是实现返回 ActionView::Renderer 对象的 view_renderer。

方法
#
R

实例公共方法

_layout_for(*args, &block)

覆盖上下文对象中的 _layout_for,以便支持将块传递给部分。返回给定名称或块后传递给布局的内容。

您可以将布局视为使用块调用的方法。如果用户调用 yield :some_name,则该块在默认情况下返回 content_for(:some_name)。如果用户仅调用 yield,则默认块返回 content_for(:layout)

用户可以通过将块传递给布局来覆盖此默认值

# The template
<%= render layout: "my_layout" do %>
  Content
<% end %>

# The layout
<html>
  <%= yield %>
</html>

在这种情况下,此方法返回传递给 render :layout 的块,而不是返回 content_for(:layout) 的默认块,响应将为

<html>
  Content
</html>

最后,该块可以采用块参数,这些参数可以通过 yield 传递

# The template
<%= render layout: "my_layout" do |customer| %>
  Hello <%= customer.name %>
<% end %>

# The layout
<html>
  <%= yield Struct.new(:name).new("David") %>
</html>

在这种情况下,布局将接收传递给 render :layout 的块,并且指定的结构将作为参数传递给该块。结果将是

<html>
  Hello David
</html>
# File actionview/lib/action_view/helpers/rendering_helper.rb, line 97
def _layout_for(*args, &block)
  name = args.first

  if block && !name.is_a?(Symbol)
    capture(*args, &block)
  else
    super
  end
end

render(options = {}, locals = {}, &block)

返回由选项哈希决定的渲染结果。主要选项是

  • :partial - 请参阅 ActionView::PartialRenderer

  • :file - 渲染一个显式模板文件(这曾经是旧的默认值),添加 :locals 以传入这些文件。

  • :inline - 渲染一个内联模板,类似于在控制器中完成的方式。

  • :plain - 渲染传入的文本。将内容类型设置为 text/plain

  • :html - 渲染传入的 HTML 安全字符串,否则首先对字符串执行 HTML 转义。将内容类型设置为 text/html

  • :body - 渲染传入的文本,并继承 text/plain 的内容类型,来自 ActionDispatch::Response 对象。

如果没有传递 options 哈希或指定了 :update,则

如果传递了一个响应 render_in 的对象,则在对象上调用 render_in,并传入当前视图上下文。

否则,使用第二个参数作为本地哈希来渲染一个部分。

# File actionview/lib/action_view/helpers/rendering_helper.rb, line 30
def render(options = {}, locals = {}, &block)
  case options
  when Hash
    in_rendering_context(options) do |renderer|
      if block_given?
        view_renderer.render_partial(self, options.merge(partial: options[:layout]), &block)
      else
        view_renderer.render(self, options)
      end
    end
  else
    if options.respond_to?(:render_in)
      options.render_in(self, &block)
    else
      view_renderer.render_partial(self, partial: options, locals: locals, &block)
    end
  end
end