跳至内容 跳至搜索

Action View 标签帮助器

提供方法以编程方式生成 HTML 标签,既可以作为符合现代 HTML5 的构建器样式,也可以作为符合传统 XHTML 的标签。

方法
B
C
E
T
包含的模块

常量

ARIA_PREFIXES = ["aria", :aria].to_set.freeze
 
BOOLEAN_ATTRIBUTES = %w(allowfullscreen allowpaymentrequest async autofocus autoplay checked compact controls declare default defaultchecked defaultmuted defaultselected defer disabled enabled formnovalidate hidden indeterminate inert ismap itemscope loop multiple muted nohref nomodule noresize noshade novalidate nowrap open pauseonexit playsinline readonly required reversed scoped seamless selected sortable truespeed typemustmatch visible).to_set
 
DATA_PREFIXES = ["data", :data].to_set.freeze
 
PRE_CONTENT_STRINGS = Hash.new { "" }
 
TAG_TYPES = {}
 

类公共方法

build_tag_values(*args)

# File actionview/lib/action_view/helpers/tag_helper.rb, line 403
def build_tag_values(*args)
  tag_values = []

  args.each do |tag_value|
    case tag_value
    when Hash
      tag_value.each do |key, val|
        tag_values << key.to_s if val && key.present?
      end
    when Array
      tag_values.concat build_tag_values(*tag_value)
    else
      tag_values << tag_value.to_s if tag_value.present?
    end
  end

  tag_values
end

实例公共方法

cdata_section(content)

返回带有给定content的 CDATA 部分。CDATA 部分用于转义包含字符的文本块,否则这些字符将被识别为标记。CDATA 部分以字符串<![CDATA[开头,以字符串]]>结尾(并且可能不包含该字符串)。

cdata_section("<hello world>")
# => <![CDATA[<hello world>]]>

cdata_section(File.read("hello_world.txt"))
# => <![CDATA[<hello from a text file]]>

cdata_section("hello]]>world")
# => <![CDATA[hello]]]]><![CDATA[>world]]>
# File actionview/lib/action_view/helpers/tag_helper.rb, line 386
def cdata_section(content)
  splitted = content.to_s.gsub(/\]\]>/, "]]]]><![CDATA[>")
  "<![CDATA[#{splitted}]]>".html_safe
end

class_names(*args)

别名:token_list

content_tag(name, content_or_options_with_block = nil, options = nil, escape = true, &block)

返回一个 HTML 块标记,类型为 name,包围 content。通过将属性哈希传递给 options 来添加 HTML 属性。除了将内容作为参数传递之外,还可以使用一个块,在这种情况下,将 options 作为第二个参数传递。将 escape 设置为 false 以禁用转义。注意:这是旧语法,有关详细信息,请参阅 tag 方法说明。

选项

options 哈希可以与没有值的属性一起使用(如 disabledreadonly),可以在 options 哈希中为其赋予 true 值。可以使用符号或字符串作为属性名称。

示例

content_tag(:p, "Hello world!")
 # => <p>Hello world!</p>
content_tag(:div, content_tag(:p, "Hello world!"), class: "strong")
 # => <div class="strong"><p>Hello world!</p></div>
content_tag(:div, "Hello world!", class: ["strong", "highlight"])
 # => <div class="strong highlight">Hello world!</div>
content_tag(:div, "Hello world!", class: ["strong", { highlight: current_user.admin? }])
 # => <div class="strong highlight">Hello world!</div>
content_tag("select", options, multiple: true)
 # => <select multiple="multiple">...options...</select>

<%= content_tag :div, class: "strong" do -%>
  Hello world!
<% end -%>
 # => <div class="strong">Hello world!</div>
# File actionview/lib/action_view/helpers/tag_helper.rb, line 346
def content_tag(name, content_or_options_with_block = nil, options = nil, escape = true, &block)
  if block_given?
    options = content_or_options_with_block if content_or_options_with_block.is_a?(Hash)
    tag_builder.content_tag_string(name, capture(&block), options, escape)
  else
    tag_builder.content_tag_string(name, content_or_options_with_block, options, escape)
  end
end

escape_once(html)

返回转义版的 html,而不影响现有的转义实体。

escape_once("1 < 2 &amp; 3")
# => "1 &lt; 2 &amp; 3"

escape_once("&lt;&lt; Accept & Checkout")
# => "&lt;&lt; Accept &amp; Checkout"
# File actionview/lib/action_view/helpers/tag_helper.rb, line 398
def escape_once(html)
  ERB::Util.html_escape_once(html)
end

tag(name = nil, options = nil, open = false, escape = true)

返回一个 HTML 标记。

构建 HTML 标记

使用标记代理构建符合 HTML5 标准的标记。每个标记都可以使用以下方式构建

tag.<tag name>(optional content, options)

其中标记名称可以是 br、div、section、article 或任何标记。

传递内容

Tags 可以传递内容以嵌入其中

tag.h1 'All titles fit to print' # => <h1>All titles fit to print</h1>

tag.div tag.p('Hello world!')  # => <div><p>Hello world!</p></div>

内容也可以通过块捕获,这在模板中很有用

<%= tag.p do %>
  The next great American novel starts here.
<% end %>
# => <p>The next great American novel starts here.</p>

选项

使用符号键控选项向生成的标记添加属性。

tag.section class: %w( kitties puppies )
# => <section class="kitties puppies"></section>

tag.section id: dom_id(@post)
# => <section id="<generated dom id>"></section>

对于任何可以不带值呈现的属性(如 disabledreadonly),请传递 true

tag.input type: 'text', disabled: true
# => <input type="text" disabled="disabled">

HTML5 data-*aria-* 属性可以使用单个 dataaria 键设置,该键指向子属性的哈希。

为了与 JavaScript 约定保持一致,子属性被连字符化。

tag.article data: { user_id: 123 }
# => <article data-user-id="123"></article>

因此,data-user-id 可以作为 dataset.userId 访问。

数据属性值被编码为 JSON,但字符串、符号和 BigDecimals 除外。在使用 jQuery 1.4.3 中支持 HTML5 的 .data() 时,这可能会派上用场。

tag.div data: { city_state: %w( Chicago IL ) }
# => <div data-city-state="[&quot;Chicago&quot;,&quot;IL&quot;]"></div>

默认情况下,生成的标签名称和属性会进行转义。可以使用 escape 禁用此功能。

tag.img src: 'open & shut.png'
# => <img src="open &amp; shut.png">

tag.img src: 'open & shut.png', escape: false
# => <img src="open & shut.png">

如果未传递内容,标签生成器会遵守 HTML5 空元素,并省略这些元素的结束标签。

# A standard element:
tag.div # => <div></div>

# A void element:
tag.br  # => <br>

生成 HTML 属性

Hash 转换为 HTML 属性,以便内插到 ERB 中。根据布尔值包含或省略布尔属性。将嵌套在 aria:data: 对象中的键转换为以 aria-data- 为前缀的属性

<input <%= tag.attributes(type: :text, aria: { label: "Search" }) %>>
# => <input type="text" aria-label="Search">

<button <%= tag.attributes id: "call-to-action", disabled: false, aria: { expanded: false } %> class="primary">Get Started!</button>
# => <button id="call-to-action" aria-expanded="false" class="primary">Get Started!</button>

旧语法

以下格式用于支持旧语法。它将在未来版本的 Rails 中弃用。

tag(name, options = nil, open = false, escape = true)

它返回一个空 HTML 标签,类型为 name,默认情况下符合 XHTML 标准。将 open 设置为 true 以创建与 HTML 4.0 及更低版本兼容的开放标签。通过将属性哈希传递给 options 来添加 HTML 属性。将 escape 设置为 false 以禁用属性值转义。

选项

你可以对属性名称使用符号或字符串。

对可以不带值呈现的布尔属性(如 disabledreadonly)使用 true

HTML5 data-* 属性可以使用单个 data 键设置,该键指向子属性的哈希。

示例

tag("br")
# => <br />

tag("br", nil, true)
# => <br>

tag("input", type: 'text', disabled: true)
# => <input type="text" disabled="disabled" />

tag("input", type: 'text', class: ["strong", "highlight"])
# => <input class="strong highlight" type="text" />

tag("img", src: "open & shut.png")
# => <img src="open &amp; shut.png" />

tag("img", { src: "open &amp; shut.png" }, false, false)
# => <img src="open &amp; shut.png" />

tag("div", data: { name: 'Stephen', city_state: %w(Chicago IL) })
# => <div data-name="Stephen" data-city-state="[&quot;Chicago&quot;,&quot;IL&quot;]" />

tag("div", class: { highlight: current_user.admin? })
# => <div class="highlight" />
# File actionview/lib/action_view/helpers/tag_helper.rb, line 309
def tag(name = nil, options = nil, open = false, escape = true)
  if name.nil?
    tag_builder
  else
    name = ERB::Util.xml_name_escape(name) if escape
    "<#{name}#{tag_builder.tag_options(options, escape) if options}#{open ? ">" : " />"}".html_safe
  end
end

token_list(*args)

返回由 args 构建的令牌字符串。

示例

token_list("foo", "bar")
 # => "foo bar"
token_list("foo", "foo bar")
 # => "foo bar"
token_list({ foo: true, bar: false })
 # => "foo"
token_list(nil, false, 123, "", "foo", { bar: true })
 # => "123 foo bar"
别名:class_names
# File actionview/lib/action_view/helpers/tag_helper.rb, line 366
def token_list(*args)
  tokens = build_tag_values(*args).flat_map { |value| CGI.unescape_html(value.to_s).split(/\s+/) }.uniq

  safe_join(tokens, " ")
end