跳至内容 跳至搜索

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 171
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 186
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 297
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 276
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 %>
# File actionview/lib/action_view/template.rb, line 152
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 210
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 248
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
      view._run(method_name, self, locals, OutputBuffer.new, add_to_stack: add_to_stack, has_strict_locals: strict_locals?, &block)&.to_s
    end
  end
rescue => e
  handle_render_error(view, e)
end

short_identifier()

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

source()

# File actionview/lib/action_view/template.rb, line 280
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 342
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 356
def strict_locals?
  strict_locals!
end

supports_streaming?()

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

# File actionview/lib/action_view/template.rb, line 238
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 228
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 268
def type
  @type ||= Types[format]
end

实例私有方法

instrument(action, &block)

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