跳至内容 跳至搜索

Action View 模板

命名空间
方法
E
I
L
M
N
R
S
T

常量

NONE = Object.new
 
STRICT_LOCALS_REGEX = /\#\s+locals:\s+\((.*)\)/
 

属性

[R] format
[RW] frozen_string_literal
[R] handler
[R] identifier
[R] variable
[R] variant
[R] virtual_path

类公共方法

mime_types_implementation=(implementation)

# File actionview/lib/action_view/template.rb, line 184
def mime_types_implementation=(implementation)
  # This method isn't thread-safe, but it's not supposed
  # to be called after initialization
  if self::Types != implementation
    remove_const(:Types)
    const_set(:Types, implementation)
  end
end

new(source, identifier, handler, locals:, format: nil, variant: nil, virtual_path: nil)

# File actionview/lib/action_view/template.rb, line 199
def initialize(source, identifier, handler, locals:, format: nil, variant: nil, virtual_path: nil)
  @source            = source.dup
  @identifier        = identifier
  @handler           = handler
  @compiled          = false
  @locals            = locals
  @virtual_path      = virtual_path

  @variable = if @virtual_path
    base = @virtual_path.end_with?("/") ? "" : ::File.basename(@virtual_path)
    base =~ /\A_?(.*?)(?:\.\w+)*\z/
    $1.to_sym
  end

  @format            = format
  @variant           = variant
  @compile_mutex     = Mutex.new
  @strict_locals     = NONE
  @strict_local_keys = nil
  @type              = nil
end

实例公共方法

encode!()

此方法负责正确设置源的编码。在此之前,我们假设源是二进制数据。如果没有提供其他信息,我们假设编码与 Encoding.default_external 相同。

用户也可以通过模板第一行的注释指定编码(# encoding: NAME-OF-ENCODING)。这将适用于任何模板引擎,因为我们在将源传递给模板引擎之前处理掉了编码注释,并在其位置留下了空白行。

# File actionview/lib/action_view/template.rb, line 321
def encode!
  source = self.source

  return source unless source.encoding == Encoding::BINARY

  # Look for # encoding: *. If we find one, we'll encode the
  # String in that encoding, otherwise, we'll use the
  # default external encoding.
  if source.sub!(LEADING_ENCODING_REGEXP, "")
    encoding = magic_encoding = $1
  else
    encoding = Encoding.default_external
  end

  # Tag the source with the default external encoding
  # or the encoding specified in the file
  source.force_encoding(encoding)

  # If the user didn't specify an encoding, and the handler
  # handles encodings, we simply pass the String as is to
  # the handler (with the default_external tag)
  if !magic_encoding && @handler.respond_to?(:handles_encoding?) && @handler.handles_encoding?
    source
  # Otherwise, if the String is valid in the encoding,
  # encode immediately to default_internal. This means
  # that if a handler doesn't handle encodings, it will
  # always get Strings in the default_internal
  elsif source.valid_encoding?
    source.encode!
  # Otherwise, since the String is invalid in the encoding
  # specified, raise an exception
  else
    raise WrongEncodingError.new(source, encoding)
  end
end

inspect()

# File actionview/lib/action_view/template.rb, line 300
def inspect
  "#<#{self.class.name} #{short_identifier} locals=#{locals.inspect}>"
end

local_assigns

返回一个包含定义的局部变量的哈希。

给定此子模板渲染

<%= render "application/header", { headline: "Welcome", person: person } %>

您可以在子模板中使用 local_assigns 来访问局部变量

local_assigns[:headline] # => "Welcome"

local_assigns 中的每个键都可用作局部变量

local_assigns[:headline] # => "Welcome"
headline                 # => "Welcome"

由于 local_assigns 是一个 Hash,它与 Ruby 3.1 的模式匹配赋值运算符兼容

local_assigns => { headline:, **options }
headline                 # => "Welcome"
options                  # => {}

模式匹配赋值也支持变量重命名

local_assigns => { headline: title }
title                    # => "Welcome"

如果模板引用一个没有作为 locals: { ... } Hash 的一部分传递给视图的变量,模板将引发 ActionView::Template::Error

<%# => raises ActionView::Template::Error %>
<% alerts.each do |alert| %>
  <p><%= alert %></p>
<% end %>

由于 local_assigns 返回一个 Hash 实例,因此您可以有条件地读取变量,然后在键不是 locals: { ... } 选项的一部分时回退到默认值

<% local_assigns.fetch(:alerts, []).each do |alert| %>
  <p><%= alert %></p>
<% end %>

将 Ruby 3.1 的模式匹配赋值与对 +Hash#with_defaults+ 的调用结合使用,可以实现紧凑的局部变量赋值

<% local_assigns.with_defaults(alerts: []) => { headline:, alerts: } %>

<h1><%= headline %></h1>

<% alerts.each do |alert| %>
  <p><%= alert %></p>
<% end %>

默认情况下,模板将接受任何 locals 作为关键字参数,并使它们可供 local_assigns 使用。要限制模板将接受哪些 local_assigns,请添加一个 locals: 魔法注释

<%# locals: (headline:, alerts: []) %>

<h1><%= headline %></h1>

<% alerts.each do |alert| %>
  <p><%= alert %></p>
<% end %>

在指南中了解更多关于严格局部变量的信息 Action View 概述

# File actionview/lib/action_view/template.rb, line 165
eager_autoload do
  autoload :Error
  autoload :RawFile
  autoload :Renderable
  autoload :Handlers
  autoload :HTML
  autoload :Inline
  autoload :Types
  autoload :Sources
  autoload :Text
  autoload :Types
end

locals()

此模板已编译或将编译的局部变量,如果这是严格局部变量模板,则为 nil。

# File actionview/lib/action_view/template.rb, line 223
def locals
  if strict_locals?
    nil
  else
    @locals
  end
end

render(view, locals, buffer = nil, implicit_locals: [], add_to_stack: true, &block)

渲染模板。如果模板尚未编译,则会在渲染前完成编译。

此方法被检测为“!render_template.action_view”。请注意,我们在检测中使用了感叹号,因为您不想在生产环境中使用它。只有在被监听时,它才速度慢。

# File actionview/lib/action_view/template.rb, line 271
def render(view, locals, buffer = nil, implicit_locals: [], add_to_stack: true, &block)
  instrument_render_template do
    compile!(view)

    if strict_locals? && @strict_local_keys && !implicit_locals.empty?
      locals_to_ignore = implicit_locals - @strict_local_keys
      locals.except!(*locals_to_ignore)
    end

    if buffer
      view._run(method_name, self, locals, buffer, add_to_stack: add_to_stack, has_strict_locals: strict_locals?, &block)
      nil
    else
      result = view._run(method_name, self, locals, OutputBuffer.new, add_to_stack: add_to_stack, has_strict_locals: strict_locals?, &block)
      result.is_a?(OutputBuffer) ? result.to_s : result
    end
  end
rescue => e
  handle_render_error(view, e)
end

short_identifier()

# File actionview/lib/action_view/template.rb, line 296
def short_identifier
  @short_identifier ||= defined?(Rails.root) ? identifier.delete_prefix("#{Rails.root}/") : identifier
end

source()

# File actionview/lib/action_view/template.rb, line 304
def source
  @source.to_s
end

strict_locals!()

此方法负责将模板标记为具有严格局部变量,这意味着模板只能接受在魔法注释中定义的局部变量。例如,如果您的模板接受局部变量 titlecomment_count,请将以下内容添加到您的模板文件中

<%# locals: (title: "Default title", comment_count: 0) %>

严格局部变量对于验证模板参数和指定默认值非常有用。

# File actionview/lib/action_view/template.rb, line 366
def strict_locals!
  if @strict_locals == NONE
    self.source.sub!(STRICT_LOCALS_REGEX, "")
    @strict_locals = $1

    return if @strict_locals.nil? # Magic comment not found

    @strict_locals = "**nil" if @strict_locals.blank?
  end

  @strict_locals
end

strict_locals?()

返回模板是否使用严格局部变量。

# File actionview/lib/action_view/template.rb, line 380
def strict_locals?
  strict_locals!
end

supports_streaming?()

返回底层处理程序是否支持流式传输。如果是,则在开始渲染时可以传递一个流式缓冲区。

# File actionview/lib/action_view/template.rb, line 261
def supports_streaming?
  handler.respond_to?(:supports_streaming?) && handler.supports_streaming?
end

translate_location(backtrace_location, spot)

将 ErrorHighlight 返回的错误位置转换为模板中正确的源位置。

# File actionview/lib/action_view/template.rb, line 251
def translate_location(backtrace_location, spot)
  if handler.respond_to?(:translate_location)
    handler.translate_location(spot, backtrace_location, encode!) || spot
  else
    spot
  end
end

type()

# File actionview/lib/action_view/template.rb, line 292
def type
  @type ||= Types[format]
end

实例私有方法

instrument(action, &block)

# File actionview/lib/action_view/template.rb, line 578
def instrument(action, &block) # :doc:
  ActiveSupport::Notifications.instrument("#{action}.action_view", instrument_payload, &block)
end