Module: ActionView::Helpers::AssetTagHelper
- Extended by:
- ActiveSupport::Concern
- Includes:
- AssetUrlHelper, TagHelper
- Included in:
- ActionView::Helpers
- Defined in:
- lib/action_view/helpers/asset_tag_helper.rb
Overview
This module provides methods for generating HTML that links views to assets such as images, JavaScripts, stylesheets, and feeds. These methods do not verify the assets exist before linking to them:
image_tag("rails.png")
# => <img src="/assets/rails.png" />
stylesheet_link_tag("application")
# => <link href="/assets/application.css?body=1" media="screen" rel="stylesheet" />
Constant Summary
Constants included from TagHelper
TagHelper::ARIA_PREFIXES, TagHelper::BOOLEAN_ATTRIBUTES, TagHelper::DATA_PREFIXES, TagHelper::PRE_CONTENT_STRINGS, TagHelper::TAG_TYPES
Constants included from AssetUrlHelper
ActionView::Helpers::AssetUrlHelper::ASSET_EXTENSIONS, ActionView::Helpers::AssetUrlHelper::ASSET_PUBLIC_DIRECTORIES, ActionView::Helpers::AssetUrlHelper::URI_REGEXP
Instance Method Summary collapse
-
#audio_tag(*sources) ⇒ Object
Returns an HTML audio tag for the
sources
. -
#auto_discovery_link_tag(type = :rss, url_options = {}, tag_options = {}) ⇒ Object
Returns a link tag that browsers and feed readers can use to auto-detect an RSS, Atom, or JSON feed.
-
#favicon_link_tag(source = "favicon.ico", options = {}) ⇒ Object
Returns a link tag for a favicon managed by the asset pipeline.
-
#image_tag(source, options = {}) ⇒ Object
Returns an HTML image tag for the
source
. -
#javascript_include_tag(*sources) ⇒ Object
Returns an HTML script tag for each of the
sources
provided. -
#preload_link_tag(source, options = {}) ⇒ Object
Returns a link tag that browsers can use to preload the
source
. -
#stylesheet_link_tag(*sources) ⇒ Object
Returns a stylesheet link tag for the sources specified as arguments.
-
#video_tag(*sources) ⇒ Object
Returns an HTML video tag for the
sources
.
Methods included from TagHelper
build_tag_values, #cdata_section, #content_tag, #escape_once, #tag, #token_list
Methods included from OutputSafetyHelper
#raw, #safe_join, #to_sentence
Methods included from CaptureHelper
#capture, #content_for, #content_for?, #provide, #with_output_buffer
Methods included from AssetUrlHelper
#asset_path, #asset_url, #audio_path, #audio_url, #compute_asset_extname, #compute_asset_host, #compute_asset_path, #font_path, #font_url, #image_path, #image_url, #javascript_path, #javascript_url, #stylesheet_path, #stylesheet_url, #video_path, #video_url
Instance Method Details
#audio_tag(*sources) ⇒ Object
Returns an HTML audio tag for the sources
. If sources
is a string, a single audio tag will be returned. If sources
is an array, an audio tag with nested source tags for each source will be returned. The sources
can be full paths or files that exist in your public audios directory.
When the last parameter is a hash you can add HTML attributes using that parameter.
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>
458 459 460 |
# File 'lib/action_view/helpers/asset_tag_helper.rb', line 458 def audio_tag(*sources) multiple_sources_tag_builder("audio", sources) end |
#auto_discovery_link_tag(type = :rss, url_options = {}, tag_options = {}) ⇒ Object
Returns a link tag that browsers and feed readers can use to auto-detect an RSS, Atom, or JSON feed. The type
can be :rss
(default), :atom
, or :json
. Control the link options in url_for format using the url_options
. You can modify the LINK tag itself in tag_options
.
Options
-
:rel
- Specify the relation of this link, defaults to “alternate” -
:type
- Override the auto-generated mime type -
:title
- Specify the title of the link, defaults to thetype
Examples
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" />
212 213 214 215 216 217 218 219 220 221 222 223 224 |
# File 'lib/action_view/helpers/asset_tag_helper.rb', line 212 def auto_discovery_link_tag(type = :rss, = {}, = {}) if !(type == :rss || type == :atom || type == :json) && [:type].blank? raise ArgumentError.new("You should pass :type tag_option key explicitly, because you have passed #{type} type other than :rss, :atom, or :json.") end tag( "link", "rel" => [:rel] || "alternate", "type" => [:type] || Template::Types[type].to_s, "title" => [:title] || type.to_s.upcase, "href" => .is_a?(Hash) ? url_for(.merge(only_path: false)) : ) end |
#favicon_link_tag(source = "favicon.ico", options = {}) ⇒ Object
Returns a link tag for a favicon managed by the asset pipeline.
If a page has no link like the one generated by this helper, browsers ask for /favicon.ico
automatically, and cache the file if the request succeeds. If the favicon changes it is hard to get it updated.
To have better control applications may let the asset pipeline manage their favicon storing the file under app/assets/images
, and using this helper to generate its corresponding link tag.
The helper gets the name of the favicon file as first argument, which defaults to “favicon.ico”, and also supports :rel
and :type
options to override their defaults, “shortcut icon” and “image/x-icon” respectively:
favicon_link_tag
# => <link href="/assets/favicon.ico" rel="shortcut icon" type="image/x-icon" />
favicon_link_tag 'myicon.ico'
# => <link href="/assets/myicon.ico" rel="shortcut icon" type="image/x-icon" />
Mobile Safari looks for a different link tag, pointing to an image that will be used if you add the page to the home screen of an iOS device. The following call would generate such a tag:
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" />
253 254 255 256 257 258 259 |
# File 'lib/action_view/helpers/asset_tag_helper.rb', line 253 def favicon_link_tag(source = "favicon.ico", = {}) tag("link", { rel: "shortcut icon", type: "image/x-icon", href: path_to_image(source, skip_pipeline: .delete(:skip_pipeline)) }.merge!(.symbolize_keys)) end |
#image_tag(source, options = {}) ⇒ Object
Returns an HTML image tag for the source
. The source
can be a full path, a file, or an Active Storage attachment.
Options
You can add HTML attributes using the options
. The options
supports additional keys for convenience and conformance:
-
:size
- Supplied as “WidthxHeight” or “Number”, so “30x45” becomes width=“30” and height=“45”, and “50” becomes width=“50” and height=“50”.:size
will be ignored if the value is not in the correct format. -
:srcset
- If supplied as a hash or array of[source, descriptor]
pairs, each image path will be expanded before the list is formatted as a string.
Examples
Assets (images that are part of your app):
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 blobs (images that are uploaded by the users of your app):
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" />
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 |
# File 'lib/action_view/helpers/asset_tag_helper.rb', line 370 def image_tag(source, = {}) = .symbolize_keys check_for_image_tag_errors() skip_pipeline = .delete(:skip_pipeline) [:src] = resolve_image_source(source, skip_pipeline) if [:srcset] && ![:srcset].is_a?(String) [:srcset] = [:srcset].map do |src_path, size| src_path = path_to_image(src_path, skip_pipeline: skip_pipeline) "#{src_path} #{size}" end.join(", ") end [:width], [:height] = extract_dimensions(.delete(:size)) if [:size] tag("img", ) end |
#javascript_include_tag(*sources) ⇒ Object
Returns an HTML script tag for each of the sources
provided.
Sources may be paths to JavaScript files. Relative paths are assumed to be relative to assets/javascripts
, full paths are assumed to be relative to the document root. Relative paths are idiomatic, use absolute paths only when needed.
When passing paths, the “.js” extension is optional. If you do not want “.js” appended to the path extname: false
can be set on the options.
You can modify the HTML attributes of the script tag by passing a hash as the last argument.
When the Asset Pipeline is enabled, you can pass the name of your manifest as source, and include other JavaScript or CoffeeScript files inside the manifest.
If the server supports Early Hints header links for these assets will be automatically pushed.
Options
When the last parameter is a hash you can add HTML attributes using that parameter. The following options are supported:
-
:extname
- Append an extension to the generated URL unless the extension already exists. This only applies for relative URLs. -
:protocol
- Sets the protocol of the generated URL. This option only applies when a relative URL andhost
options are provided. -
:host
- When a relative URL is provided the host is added to the that path. -
:skip_pipeline
- This option is used to bypass the asset pipeline when it is set to true. -
:nonce
- When set to true, adds an automatic nonce value if you have Content Security Policy enabled.
Examples
javascript_include_tag "xmlhr"
# => <script src="/assets/xmlhr.debug-1284139606.js"></script>
javascript_include_tag "xmlhr", host: "localhost", protocol: "https"
# => <script src="https://localhost/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>
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 |
# File 'lib/action_view/helpers/asset_tag_helper.rb', line 88 def javascript_include_tag(*sources) = sources..stringify_keys = .extract!("protocol", "extname", "host", "skip_pipeline").symbolize_keys preload_links = [] nopush = ["nopush"].nil? ? true : .delete("nopush") crossorigin = .delete("crossorigin") crossorigin = "anonymous" if crossorigin == true integrity = ["integrity"] = sources.uniq.map { |source| href = path_to_javascript(source, ) if preload_links_header && !["defer"] preload_link = "<#{href}>; rel=preload; 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 = { "src" => href, "crossorigin" => crossorigin }.merge!() if ["nonce"] == true ["nonce"] = content_security_policy_nonce end content_tag("script", "", ) }.join("\n").html_safe if preload_links_header send_preload_links_header(preload_links) end end |
#preload_link_tag(source, options = {}) ⇒ Object
Returns a link tag that browsers can use to preload the source
. The source
can be the path of a resource managed by asset pipeline, a full path, or an URI.
Options
-
:type
- Override the auto-generated mime type, defaults to the mime type forsource
extension. -
:as
- Override the auto-generated value for as attribute, calculated usingsource
extension and mime type. -
:crossorigin
- Specify the crossorigin attribute, required to load cross-origin resources. -
:nopush
- Specify if the use of server push is not desired for the resource. Defaults tofalse
. -
:integrity
- Specify the integrity attribute.
Examples
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" />
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 |
# File 'lib/action_view/helpers/asset_tag_helper.rb', line 296 def preload_link_tag(source, = {}) href = asset_path(source, skip_pipeline: .delete(:skip_pipeline)) extname = File.extname(source).downcase.delete(".") mime_type = .delete(:type) || Template::Types[extname]&.to_s as_type = .delete(:as) || resolve_link_as(extname, mime_type) crossorigin = .delete(:crossorigin) crossorigin = "anonymous" if crossorigin == true || (crossorigin.blank? && as_type == "font") integrity = [:integrity] nopush = .delete(:nopush) || false link_tag = tag.link(**{ rel: "preload", href: href, as: as_type, type: mime_type, crossorigin: crossorigin }.merge!(.symbolize_keys)) preload_link = "<#{href}>; rel=preload; as=#{as_type}" preload_link += "; type=#{mime_type}" if mime_type preload_link += "; crossorigin=#{crossorigin}" if crossorigin preload_link += "; integrity=#{integrity}" if integrity preload_link += "; nopush" if nopush send_preload_links_header([preload_link]) link_tag end |
#stylesheet_link_tag(*sources) ⇒ Object
Returns a stylesheet link tag for the sources specified as arguments. If you don’t specify an extension, .css
will be appended automatically. You can modify the link attributes by passing a hash as the last argument. For historical reasons, the ‘media’ attribute will always be present and defaults to “screen”, so you must explicitly set it to “all” for the stylesheet(s) to apply to all media types.
If the server supports Early Hints header links for these assets will be automatically pushed.
stylesheet_link_tag "style"
# => <link href="/assets/style.css" media="screen" rel="stylesheet" />
stylesheet_link_tag "style.css"
# => <link href="/assets/style.css" media="screen" rel="stylesheet" />
stylesheet_link_tag "http://www.example.com/style.css"
# => <link href="http://www.example.com/style.css" media="screen" rel="stylesheet" />
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" media="screen" rel="stylesheet" />
# <link href="/css/stylish.css" media="screen" rel="stylesheet" />
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 |
# File 'lib/action_view/helpers/asset_tag_helper.rb', line 151 def stylesheet_link_tag(*sources) = sources..stringify_keys = .extract!("protocol", "host", "skip_pipeline").symbolize_keys preload_links = [] crossorigin = .delete("crossorigin") crossorigin = "anonymous" if crossorigin == true nopush = ["nopush"].nil? ? true : .delete("nopush") integrity = ["integrity"] = sources.uniq.map { |source| href = path_to_stylesheet(source, ) if preload_links_header preload_link = "<#{href}>; rel=preload; as=style" preload_link += "; crossorigin=#{crossorigin}" unless crossorigin.nil? preload_link += "; integrity=#{integrity}" unless integrity.nil? preload_link += "; nopush" if nopush preload_links << preload_link end = { "rel" => "stylesheet", "media" => "screen", "crossorigin" => crossorigin, "href" => href }.merge!() tag(:link, ) }.join("\n").html_safe if preload_links_header send_preload_links_header(preload_links) end end |
#video_tag(*sources) ⇒ Object
Returns an HTML video tag for the sources
. If sources
is a string, a single video tag will be returned. If sources
is an array, a video tag with nested source tags for each source will be returned. The sources
can be full paths or files that exist in your public videos directory.
Options
When the last parameter is a hash you can add HTML attributes using that parameter. The following options are supported:
-
:poster
- Set an image (like a screenshot) to be shown before the video loads. The path is calculated like thesrc
ofimage_tag
. -
:size
- Supplied as “WidthxHeight” or “Number”, so “30x45” becomes width=“30” and height=“45”, and “50” becomes width=“50” and height=“50”.:size
will be ignored if the value is not in the correct format. -
:poster_skip_pipeline
will bypass the asset pipeline when using the:poster
option instead using an asset in the public folder.
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>
431 432 433 434 435 436 437 438 439 |
# File 'lib/action_view/helpers/asset_tag_helper.rb', line 431 def video_tag(*sources) = sources..symbolize_keys public_poster_folder = .delete(:poster_skip_pipeline) sources << multiple_sources_tag_builder("video", sources) do || [:poster] = path_to_image([:poster], skip_pipeline: public_poster_folder) if [:poster] [:width], [:height] = extract_dimensions(.delete(:size)) if [:size] end end |