跳至内容 跳至搜索

Action View Asset Tag Helpers

此模块提供用于生成 HTML 的方法,该 HTML 将视图链接到图像、JavaScript、样式表和 Feed 等资产。这些方法在链接到资产之前不验证资产是否存在。

image_tag("rails.png")
# => <img src="/assets/rails.png" />
stylesheet_link_tag("application")
# => <link href="/assets/application.css?body=1" rel="stylesheet" />
方法
A
F
I
J
P
S
V
包含的模块

实例公共方法

audio_tag(*sources)

返回 sources 的 HTML 音频标签。如果 sources 是字符串,将返回单个音频标签。如果 sources 是数组,将返回带有嵌套 source 标签的音频标签。sources 可以是完整路径、您的公共 audio 目录中存在的文件或 Active Storage 附件。

当最后一个参数是哈希时,您可以使用该参数添加 HTML 属性。

audio_tag("sound")
# => <audio src="/audios/sound"></audio>
audio_tag("sound.wav")
# => <audio src="/audios/sound.wav"></audio>
audio_tag("sound.wav", autoplay: true, controls: true)
# => <audio autoplay="autoplay" controls="controls" src="/audios/sound.wav"></audio>
audio_tag("sound.wav", "sound.mid")
# => <audio><source src="/audios/sound.wav" /><source src="/audios/sound.mid" /></audio>

Active Storage blob(用户上传的音频)

audio_tag(user.name_pronunciation_audio)
# => <audio src="/rails/active_storage/blobs/.../name_pronunciation_audio.mp3"></audio>
# File actionview/lib/action_view/helpers/asset_tag_helper.rb, line 612
def audio_tag(*sources)
  multiple_sources_tag_builder("audio", sources)
end

返回一个链接标签,浏览器和 Feed 阅读器可以使用该标签自动检测 RSS、Atom 或 JSON Feed。type 可以是 :rss(默认)、:atom:json。使用 url_optionsurl_for 格式控制链接选项。您可以修改 tag_options 中的 LINK 标签本身。

  • :rel - 指定此链接的关系,默认为“alternate”

  • :type - 覆盖自动生成的 MIME 类型

  • :title - 指定链接的标题,默认为 type

auto_discovery_link_tag
# => <link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.currenthost.com/controller/action" />
auto_discovery_link_tag(:atom)
# => <link rel="alternate" type="application/atom+xml" title="ATOM" href="http://www.currenthost.com/controller/action" />
auto_discovery_link_tag(:json)
# => <link rel="alternate" type="application/json" title="JSON" href="http://www.currenthost.com/controller/action" />
auto_discovery_link_tag(:rss, {action: "feed"})
# => <link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.currenthost.com/controller/feed" />
auto_discovery_link_tag(:rss, {action: "feed"}, {title: "My RSS"})
# => <link rel="alternate" type="application/rss+xml" title="My RSS" href="http://www.currenthost.com/controller/feed" />
auto_discovery_link_tag(:rss, {controller: "news", action: "feed"})
# => <link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.currenthost.com/news/feed" />
auto_discovery_link_tag(:rss, "http://www.example.com/feed.rss", {title: "Example RSS"})
# => <link rel="alternate" type="application/rss+xml" title="Example RSS" href="http://www.example.com/feed.rss" />

返回一个由资产管道管理的 favicon 的链接标签。

如果页面没有像此帮助程序生成的链接,浏览器会自动请求 /favicon.ico,并在请求成功时缓存该文件。如果 favicon 发生更改,则很难更新。

为了更好地控制,应用程序可以允许资产管道管理其 favicon,将文件存储在 app/assets/images 下,并使用此帮助程序生成相应的链接标签。

此帮助程序将 favicon 文件名作为第一个参数,默认为“favicon.ico”,还支持 :rel:type 选项来覆盖其默认值“icon”和“image/x-icon”。

favicon_link_tag
# => <link href="/assets/favicon.ico" rel="icon" type="image/x-icon" />

favicon_link_tag 'myicon.ico'
# => <link href="/assets/myicon.ico" rel="icon" type="image/x-icon" />

Mobile Safari 会查找不同的链接标签,指向一个将用于将页面添加到 iOS 设备主屏幕的图像。以下调用将生成这样的标签。

favicon_link_tag 'mb-icon.png', rel: 'apple-touch-icon', type: 'image/png'
# => <link href="/assets/mb-icon.png" rel="apple-touch-icon" type="image/png" />

image_tag(source, options = {})

返回 source 的 HTML 图像标签。source 可以是完整路径、文件或 Active Storage 附件。

Options

您可以使用 options 添加 HTML 属性。options 支持其他键以方便和合规。

  • :size - 提供为 "#{width}x#{height}""#{number}",因此 "30x45" 将变为 width="30" height="45",而 "50" 将变为 width="50" height="50"。如果值格式不正确,将忽略 :size

  • :srcset - 如果提供为哈希或 [source, descriptor] 对的数组,则每个图像路径将在列表格式化为字符串之前进行扩展。

Examples

Assets(应用程序的一部分图像)

image_tag("icon")
# => <img src="/assets/icon" />
image_tag("icon.png")
# => <img src="/assets/icon.png" />
image_tag("icon.png", size: "16x10", alt: "Edit Entry")
# => <img src="/assets/icon.png" width="16" height="10" alt="Edit Entry" />
image_tag("/icons/icon.gif", size: "16")
# => <img src="/icons/icon.gif" width="16" height="16" />
image_tag("/icons/icon.gif", height: '32', width: '32')
# => <img height="32" src="/icons/icon.gif" width="32" />
image_tag("/icons/icon.gif", class: "menu_icon")
# => <img class="menu_icon" src="/icons/icon.gif" />
image_tag("/icons/icon.gif", data: { title: 'Rails Application' })
# => <img data-title="Rails Application" src="/icons/icon.gif" />
image_tag("icon.png", srcset: { "icon_2x.png" => "2x", "icon_4x.png" => "4x" })
# => <img src="/assets/icon.png" srcset="/assets/icon_2x.png 2x, /assets/icon_4x.png 4x">
image_tag("pic.jpg", srcset: [["pic_1024.jpg", "1024w"], ["pic_1980.jpg", "1980w"]], sizes: "100vw")
# => <img src="/assets/pic.jpg" srcset="/assets/pic_1024.jpg 1024w, /assets/pic_1980.jpg 1980w" sizes="100vw">

Active Storage blob(用户上传的图像)

image_tag(user.avatar)
# => <img src="/rails/active_storage/blobs/.../tiger.jpg" />
image_tag(user.avatar.variant(resize_to_limit: [100, 100]))
# => <img src="/rails/active_storage/representations/.../tiger.jpg" />
image_tag(user.avatar.variant(resize_to_limit: [100, 100]), size: '100')
# => <img width="100" height="100" src="/rails/active_storage/representations/.../tiger.jpg" />
# File actionview/lib/action_view/helpers/asset_tag_helper.rb, line 449
def image_tag(source, options = {})
  options = options.symbolize_keys
  check_for_image_tag_errors(options)
  skip_pipeline = options.delete(:skip_pipeline)

  options[:src] = resolve_asset_source("image", source, skip_pipeline)

  if options[:srcset] && !options[:srcset].is_a?(String)
    options[:srcset] = options[:srcset].map do |src_path, size|
      src_path = path_to_image(src_path, skip_pipeline: skip_pipeline)
      "#{src_path} #{size}"
    end.join(", ")
  end

  options[:width], options[:height] = extract_dimensions(options.delete(:size)) if options[:size]

  options[:loading] ||= image_loading if image_loading
  options[:decoding] ||= image_decoding if image_decoding

  tag("img", options)
end

javascript_include_tag(*sources)

返回提供的每个 sources 的 HTML script 标签。

Sources 可以是 JavaScript 文件的路径。相对路径假定相对于 assets/javascripts,完整路径假定相对于文档根目录。相对路径是惯用的,仅在需要时才使用绝对路径。

在传递路径时,“.js”扩展名是可选的。如果您不希望将“.js”附加到路径,可以在选项中设置 extname: false

您可以将哈希作为最后一个参数传递来修改 script 标签的 HTML 属性。

当启用 Asset Pipeline 时,您可以将清单的名称作为源传递,并在清单中包含其他 JavaScript 或 CoffeeScript 文件。

如果服务器支持 HTTP Early Hints 且未启用 defer 选项,Rails 将推送一个 103 Early Hints 响应,该响应链接到资产。

Options

当最后一个参数是哈希时,您可以使用该参数添加 HTML 属性。这包括但不限于以下选项:

  • :extname - 除非扩展名已存在,否则附加扩展名到生成的 URL。这仅适用于相对 URL。

  • :protocol - 设置生成 URL 的协议。此选项仅在提供相对 URL 和 host 选项时适用。

  • :host - 提供相对 URL 时,将主机添加到该路径。

  • :skip_pipeline - 如果设置为 true,则此选项用于绕过资产管道。

  • :nonce - 如果设置为 true,并且启用了内容安全策略,则添加一个自动 nonce 值。

  • :async - 如果设置为 true,则添加 async HTML 属性,允许脚本并行获取,并尽快解析和评估。

  • :defer - 如果设置为 true,则添加 defer HTML 属性,指示浏览器在文档解析后执行脚本。此外,它还会阻止发送 Preload Links 标头。

  • :nopush - 指定是否不希望为此脚本使用服务器推送。默认为 true

任何其他指定的选项都将被视为 script 标签的 HTML 属性。

有关 :async:defer 选项如何影响 <script> 标签的更多信息,请参阅 MDN 文档

Examples

javascript_include_tag "xmlhr"
# => <script src="/assets/xmlhr.debug-1284139606.js"></script>

javascript_include_tag "xmlhr", host: "localhost", protocol: "https"
# => <script src="https:///assets/xmlhr.debug-1284139606.js"></script>

javascript_include_tag "template.jst", extname: false
# => <script src="/assets/template.debug-1284139606.jst"></script>

javascript_include_tag "xmlhr.js"
# => <script src="/assets/xmlhr.debug-1284139606.js"></script>

javascript_include_tag "common.javascript", "/elsewhere/cools"
# => <script src="/assets/common.javascript.debug-1284139606.js"></script>
#    <script src="/elsewhere/cools.debug-1284139606.js"></script>

javascript_include_tag "http://www.example.com/xmlhr"
# => <script src="http://www.example.com/xmlhr"></script>

javascript_include_tag "http://www.example.com/xmlhr.js"
# => <script src="http://www.example.com/xmlhr.js"></script>

javascript_include_tag "http://www.example.com/xmlhr.js", nonce: true
# => <script src="http://www.example.com/xmlhr.js" nonce="..."></script>

javascript_include_tag "http://www.example.com/xmlhr.js", async: true
# => <script src="http://www.example.com/xmlhr.js" async="async"></script>

javascript_include_tag "http://www.example.com/xmlhr.js", defer: true
# => <script src="http://www.example.com/xmlhr.js" defer="defer"></script>
# File actionview/lib/action_view/helpers/asset_tag_helper.rb, line 115
def javascript_include_tag(*sources)
  options = sources.extract_options!.stringify_keys
  path_options = options.extract!("protocol", "extname", "host", "skip_pipeline").symbolize_keys
  preload_links = []
  use_preload_links_header = options["preload_links_header"].nil? ? preload_links_header : options.delete("preload_links_header")
  nopush = options["nopush"].nil? || options.delete("nopush")
  crossorigin = options.delete("crossorigin")
  crossorigin = "anonymous" if crossorigin == true
  integrity = options["integrity"]
  rel = options["type"] == "module" || options["type"] == :module ? "modulepreload" : "preload"

  sources_tags = sources.uniq.map { |source|
    href = path_to_javascript(source, path_options)
    if use_preload_links_header && !options["defer"] && href.present? && !href.start_with?("data:")
      preload_link = "<#{href}>; rel=#{rel}; as=script"
      preload_link += "; crossorigin=#{crossorigin}" unless crossorigin.nil?
      preload_link += "; integrity=#{integrity}" unless integrity.nil?
      preload_link += "; nonce=#{content_security_policy_nonce}" if options["nonce"] == true
      preload_link += "; nopush" if nopush
      preload_links << preload_link
    end
    tag_options = {
      "src" => href,
      "crossorigin" => crossorigin
    }.merge!(options)
    if tag_options["nonce"] == true || (!tag_options.key?("nonce") && auto_include_nonce_for_scripts)
      tag_options["nonce"] = content_security_policy_nonce
    elsif tag_options["nonce"] == false
      tag_options.delete("nonce")
    end
    content_tag("script", "", tag_options)
  }.join("\n").html_safe

  if use_preload_links_header
    send_preload_links_header(preload_links)
  end

  sources_tags
end

picture_tag(*sources, &block)

返回 sources 的 HTML picture 标签。如果 sources 是字符串,将返回单个 picture 标签。如果 sources 是数组,将返回带有嵌套 source 标签的 picture 标签。sources 可以是完整路径、您的公共 images 目录中存在的文件或 Active Storage 附件。由于 picture 标签需要 img 标签,您提供的最后一个元素将用于 img 标签。为了完全控制 picture 标签,可以传递一个块,该块将相应地填充标签的内容。

Options

当最后一个参数是哈希时,您可以使用该参数添加 HTML 属性。除了所有支持的 HTML 选项外,还支持以下选项:

Examples

picture_tag("picture.webp")
# => <picture><img src="/images/picture.webp" /></picture>
picture_tag("gold.png", :image => { :size => "20" })
# => <picture><img height="20" src="/images/gold.png" width="20" /></picture>
picture_tag("gold.png", :image => { :size => "45x70" })
# => <picture><img height="70" src="/images/gold.png" width="45" /></picture>
picture_tag("picture.webp", "picture.png")
# => <picture><source srcset="/images/picture.webp" /><source srcset="/images/picture.png" /><img src="/images/picture.png" /></picture>
picture_tag("picture.webp", "picture.png", :image => { alt: "Image" })
# => <picture><source srcset="/images/picture.webp" /><source srcset="/images/picture.png" /><img alt="Image" src="/images/picture.png" /></picture>
picture_tag(["picture.webp", "picture.png"], :image => { alt: "Image" })
# => <picture><source srcset="/images/picture.webp" /><source srcset="/images/picture.png" /><img alt="Image" src="/images/picture.png" /></picture>
picture_tag(:class => "my-class") { tag(:source, :srcset => image_path("picture.webp")) + image_tag("picture.png", :alt => "Image") }
# => <picture class="my-class"><source srcset="/images/picture.webp" /><img alt="Image" src="/images/picture.png" /></picture>
picture_tag { tag(:source, :srcset => image_path("picture-small.webp"), :media => "(min-width: 600px)") + tag(:source, :srcset => image_path("picture-big.webp")) + image_tag("picture.png", :alt => "Image") }
# => <picture><source srcset="/images/picture-small.webp" media="(min-width: 600px)" /><source srcset="/images/picture-big.webp" /><img alt="Image" src="/images/picture.png" /></picture>

Active Storage blob(用户上传的图像)

picture_tag(user.profile_picture)
# => <picture><img src="/rails/active_storage/blobs/.../profile_picture.webp" /></picture>
# File actionview/lib/action_view/helpers/asset_tag_helper.rb, line 510
def picture_tag(*sources, &block)
  sources.flatten!
  options = sources.extract_options!.symbolize_keys
  image_options = options.delete(:image) || {}
  skip_pipeline = options.delete(:skip_pipeline)

  content_tag("picture", options) do
    if block.present?
      capture(&block).html_safe
    elsif sources.size <= 1
      image_tag(sources.last, image_options)
    else
      source_tags = sources.map do |source|
        tag("source",
         srcset: resolve_asset_source("image", source, skip_pipeline),
         type: Template::Types[File.extname(source)[1..]]&.to_s)
      end
      safe_join(source_tags << image_tag(sources.last, image_options))
    end
  end
end

返回一个链接标签,浏览器可以使用该标签预加载 sourcesource 可以是资产管道管理的资源的路径、完整路径或 URI。

  • :type - 覆盖自动生成的 MIME 类型,默认为 source 扩展名的 MIME 类型。

  • :as - 覆盖 as 属性的自动生成值,使用 source 扩展名和 MIME 类型计算。

  • :crossorigin - 指定 crossorigin 属性,加载跨域资源所需。

  • :nopush - 指定是否不希望为此资源使用服务器推送。默认为 false

  • :integrity - 指定 integrity 属性。

preload_link_tag("custom_theme.css")
# => <link rel="preload" href="/assets/custom_theme.css" as="style" type="text/css" />

preload_link_tag("/videos/video.webm")
# => <link rel="preload" href="/videos/video.mp4" as="video" type="video/webm" />

preload_link_tag(post_path(format: :json), as: "fetch")
# => <link rel="preload" href="/posts.json" as="fetch" type="application/json" />

preload_link_tag("worker.js", as: "worker")
# => <link rel="preload" href="/assets/worker.js" as="worker" type="text/javascript" />

preload_link_tag("//example.com/font.woff2")
# => <link rel="preload" href="//example.com/font.woff2" as="font" type="font/woff2" crossorigin="anonymous"/>

preload_link_tag("//example.com/font.woff2", crossorigin: "use-credentials")
# => <link rel="preload" href="//example.com/font.woff2" as="font" type="font/woff2" crossorigin="use-credentials" />

preload_link_tag("/media/audio.ogg", nopush: true)
# => <link rel="preload" href="/media/audio.ogg" as="audio" type="audio/ogg" />

返回参数指定的源的样式表链接标签。

在传递路径时,“.css”扩展名是可选的。如果您不指定扩展名,将自动附加“.css”。如果您不希望将“.css”附加到路径,请在选项中设置 extname: false。您可以将哈希作为最后一个参数传递来修改链接属性。

如果服务器支持 HTTP Early Hints,Rails 将推送一个 103 Early Hints 响应,该响应链接到资产。

  • :extname - 除非扩展名已存在,否则附加扩展名到生成的 URL。这仅适用于相对 URL。

  • :protocol - 设置生成 URL 的协议。此选项仅在提供相对 URL 和 host 选项时适用。

  • :host - 提供相对 URL 时,将主机添加到该路径。

  • :skip_pipeline - 如果设置为 true,则此选项用于绕过资产管道。

  • :nonce - 如果设置为 true,并且启用了内容安全策略,则添加一个自动 nonce 值。

  • :nopush - 指定是否不希望为此样式表使用服务器推送。默认为 true

stylesheet_link_tag "style"
# => <link href="/assets/style.css" rel="stylesheet" />

stylesheet_link_tag "style.css"
# => <link href="/assets/style.css" rel="stylesheet" />

stylesheet_link_tag "http://www.example.com/style.css"
# => <link href="http://www.example.com/style.css" rel="stylesheet" />

stylesheet_link_tag "style.less", extname: false, skip_pipeline: true, rel: "stylesheet/less"
# => <link href="/stylesheets/style.less" rel="stylesheet/less">

stylesheet_link_tag "style", media: "all"
# => <link href="/assets/style.css" media="all" rel="stylesheet" />

stylesheet_link_tag "style", media: "print"
# => <link href="/assets/style.css" media="print" rel="stylesheet" />

stylesheet_link_tag "random.styles", "/css/stylish"
# => <link href="/assets/random.styles" rel="stylesheet" />
#    <link href="/css/stylish.css" rel="stylesheet" />

stylesheet_link_tag "style", nonce: true
# => <link href="/assets/style.css" rel="stylesheet" nonce="..." />

video_tag(*sources)

返回 sources 的 HTML video 标签。如果 sources 是字符串,将返回单个 video 标签。如果 sources 是数组,将返回带有嵌套 source 标签的 video 标签。sources 可以是完整路径、您的公共 videos 目录中存在的 文件或 Active Storage 附件。

Options

当最后一个参数是哈希时,您可以使用该参数添加 HTML 属性。支持以下选项:

  • :poster - 设置一个图像(如屏幕截图)在视频加载前显示。路径的计算方式与 image_tagsrc 相同。

  • :size - 提供为 "#{width}x#{height}""#{number}",因此 "30x45" 将变为 width="30" height="45",而 "50" 将变为 width="50" height="50"。如果值格式不正确,将忽略 :size

  • :poster_skip_pipeline 在使用 :poster 选项时将绕过资产管道,而是使用公共文件夹中的资源。

Examples

video_tag("trailer")
# => <video src="/videos/trailer"></video>
video_tag("trailer.ogg")
# => <video src="/videos/trailer.ogg"></video>
video_tag("trailer.ogg", controls: true, preload: 'none')
# => <video preload="none" controls="controls" src="/videos/trailer.ogg"></video>
video_tag("trailer.m4v", size: "16x10", poster: "screenshot.png")
# => <video src="/videos/trailer.m4v" width="16" height="10" poster="/assets/screenshot.png"></video>
video_tag("trailer.m4v", size: "16x10", poster: "screenshot.png", poster_skip_pipeline: true)
# => <video src="/videos/trailer.m4v" width="16" height="10" poster="screenshot.png"></video>
video_tag("/trailers/hd.avi", size: "16x16")
# => <video src="/trailers/hd.avi" width="16" height="16"></video>
video_tag("/trailers/hd.avi", size: "16")
# => <video height="16" src="/trailers/hd.avi" width="16"></video>
video_tag("/trailers/hd.avi", height: '32', width: '32')
# => <video height="32" src="/trailers/hd.avi" width="32"></video>
video_tag("trailer.ogg", "trailer.flv")
# => <video><source src="/videos/trailer.ogg" /><source src="/videos/trailer.flv" /></video>
video_tag(["trailer.ogg", "trailer.flv"])
# => <video><source src="/videos/trailer.ogg" /><source src="/videos/trailer.flv" /></video>
video_tag(["trailer.ogg", "trailer.flv"], size: "160x120")
# => <video height="120" width="160"><source src="/videos/trailer.ogg" /><source src="/videos/trailer.flv" /></video>

Active Storage blob(用户上传的视频)

video_tag(user.intro_video)
# => <video src="/rails/active_storage/blobs/.../intro_video.mp4"></video>
# File actionview/lib/action_view/helpers/asset_tag_helper.rb, line 580
def video_tag(*sources)
  options = sources.extract_options!.symbolize_keys
  public_poster_folder = options.delete(:poster_skip_pipeline)
  sources << options
  multiple_sources_tag_builder("video", sources) do |tag_options|
    tag_options[:poster] = path_to_image(tag_options[:poster], skip_pipeline: public_poster_folder) if tag_options[:poster]
    tag_options[:width], tag_options[:height] = extract_dimensions(tag_options.delete(:size)) if tag_options[:size]
  end
end