跳至內容 跳至搜尋

Action View Asset 標籤幫手

此模組提供用於產生 HTML 的方法,可將檢視連結到資產,例如圖片、JavaScript、樣式表和饋送。這些方法不會驗證資產在連結到它們之前是否已存在

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` 是陣列,將傳回音訊標籤,以及每個來源的巢狀來源標籤。`sources` 可以是完整路徑、存在公開音訊目錄中的檔案,或 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 儲存區 (您的應用程式使用者上傳的音訊)

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 593
def audio_tag(*sources)
  multiple_sources_tag_builder("audio", sources)
end

傳回連結標籤,瀏覽器和饋送閱讀器可以使用它自動偵測 RSS、Atom 或 JSON 饋送。`type` 可以是 `:rss` (預設值)、`atom` 或 `:json`。使用 `url_options` 以 url_for 格式控制連結選項。您可以在 `tag_options` 中修改 LINK 標籤本身。

  • :rel - 指定此連結的關係,預設為“交替”

  • :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 新增 HTML 屬性。options 支援額外的鍵以便使用及相符性

  • :size - 以 "#{width}x#{height}""#{number}" 形式提供,因此 "30x45" 變為 width="30" height="45""50" 變為 width="50" height="50"。若 :size 的值格式不正確,則將會被忽略。

  • :srcset - 如果以雜湊或 [source, descriptor] 陣列提供,在將清單格式化為字串之前,將會展開每一個圖片路徑。

範例

資產(您應用程式的一部分的圖片)

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 430
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 標籤。

來源可以是 JavaScript 檔案的路徑。假設是 assets/javascripts 的路徑,而完整路徑則假設是以文件根目錄為基準。建議使用相對路徑,僅在需要時才使用絕對路徑。

傳遞路徑時,可以使用「.js」副檔名。如果您不想將「.js」附加至路徑,可以對選項設定 extname: false

您可以透過傳遞雜湊作為最後一個引數來修改 script 標籤的 HTML 屬性。

當啟用資產管線時,您可以傳遞已發行的名稱作為來源,並納入已發行中的其他 JavaScript 或 CoffeeScript 檔案。

如果伺服器支援 HTTP Early Hints,且未啟用 defer 選項,Rails 會推送連結至資產的 103 Early Hints 回應。

選項

當最後一個參數是雜湊時,您可以使用該參數新增 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 文件

範例

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

javascript_include_tag "xmlhr", host: "localhost", protocol: "https"
# => <script src="https://127.0.0.1/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 113
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? ? true : options.delete("nopush")
  crossorigin = options.delete("crossorigin")
  crossorigin = "anonymous" if crossorigin == true
  integrity = options["integrity"]
  rel = 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 += "; nopush" if nopush
      preload_links << preload_link
    end
    tag_options = {
      "src" => href,
      "crossorigin" => crossorigin
    }.merge!(options)
    if tag_options["nonce"] == true
      tag_options["nonce"] = content_security_policy_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 是陣列,會回傳一個 picture 標籤,並為每個資源包含巢狀的 source 標籤。sources 可以是完整路徑、公用圖片目錄中的檔案或 Active Storage 附件。由於 picture 標籤需要 img 標籤,所以你提供的最後一個元素會用於 img 標籤。如要完整控制 picture 標籤,可以傳遞區塊,它會填入標籤內容。

選項

如果最後一個參數是雜湊,可以使用該參數新增 HTML 屬性。除了所有受支援的 HTML 選項之外,還支援下列項目

  • :image - 雜湊,其中的選項會直接傳遞給 image_tag 輔助函式。

範例

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 491
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

回傳瀏覽器可使用來預載 source 的連結標籤。source 可以是資產管線管理的資源路徑、完整路徑或 URI。

  • :type - 覆寫自動產生的 MIME 類型,預設為 source 副檔名的 MIME 類型。

  • :as - 覆寫 using source 副檔名和 MIME 類型計算出的 as 屬性自動產生的值。

  • :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 早期提示,Rails 會推播連結至元件的 103 早期提示 回應。

  • :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 影片標籤。如果 sources 為字串,會傳回單一影片標籤。如果 sources 為陣列,則會傳回一個包含每個來源的巢狀來源標籤的影片標籤。sources 可以是完整路徑,出現在您的公開影片目錄中的檔案,或 Active Storage 附件。

選項

當最後一個參數是雜湊時,您可以使用該參數新增 HTML 屬性。支援下列選項

  • :poster - 設定圖片(如螢幕擷圖)在影片載入前顯示。路徑是以 image_tagsrc 方式計算。

  • :size - 以 "#{width}x#{height}""#{number}" 形式提供,因此 "30x45" 變為 width="30" height="45""50" 變為 width="50" height="50"。若 :size 的值格式不正確,則將會被忽略。

  • 當使用 :poster 選項時,:poster_skip_pipeline 將略過元件管線,而使用公開資料夾中的元件。

範例

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 561
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