123456789_123456789_123456789_123456789_123456789_

Module: ActionView::Helpers::AssetTagHelper

Relationships & Source Files
Extension / Inclusion / Inheritance Descendants
Included In:
Super Chains via Extension / Inclusion / Inheritance
Instance Chain:
Defined in: actionview/lib/action_view/helpers/asset_tag_helper.rb

Overview

Action View Asset Tag Helpers

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" rel="stylesheet" />

Constant Summary

AssetUrlHelper - Included

ASSET_EXTENSIONS, ASSET_PUBLIC_DIRECTORIES, URI_REGEXP

TagHelper - Included

ARIA_PREFIXES, BOOLEAN_ATTRIBUTES, DATA_PREFIXES, PRE_CONTENT_STRINGS, TAG_TYPES

Class Attribute Summary

Instance Attribute Summary

Instance Method Summary

TagHelper - Included

#cdata_section

Returns a CDATA section with the given content.

#class_names
#content_tag

Returns an HTML block tag of type name surrounding the content.

#escape_once

Returns an escaped version of html without affecting existing escaped entities.

#tag

Returns an HTML tag.

#token_list

Returns a string of tokens built from args.

#build_tag_values, #ensure_valid_html5_tag_name, #tag_builder

OutputSafetyHelper - Included

#raw

This method outputs without escaping a string.

#safe_join

This method returns an HTML safe string similar to what Array#join would return.

#to_sentence

Converts the array to a comma-separated sentence where the last element is joined by the connector word.

CaptureHelper - Included

#capture

The capture method extracts part of a template as a string object.

#content_for

Calling content_for stores a block of markup in an identifier for later use.

#content_for?

content_for? checks whether any content has been captured yet using content_for.

#provide

The same as content_for but when used with streaming flushes straight back to the layout.

#with_output_buffer

Use an alternate output buffer for the duration of the block.

AssetUrlHelper - Included

#asset_path

This is the entry point for all assets.

#asset_url

Computes the full URL to an asset in the public directory.

#audio_path

Computes the path to an audio asset in the public audios directory.

#audio_url

Computes the full URL to an audio asset in the public audios directory.

#compute_asset_extname

Compute extname to append to asset path.

#compute_asset_host

Pick an asset host for this source.

#compute_asset_path

Computes asset path to public directory.

#font_path

Computes the path to a font asset.

#font_url

Computes the full URL to a font asset.

#image_path

Computes the path to an image asset.

#image_url

Computes the full URL to an image asset.

#javascript_path

Computes the path to a JavaScript asset in the public javascripts directory.

#javascript_url

Computes the full URL to a JavaScript asset in the public javascripts directory.

#path_to_asset
#path_to_audio
#path_to_font
#path_to_image
#path_to_javascript
#path_to_stylesheet
#path_to_video
#public_compute_asset_path
#stylesheet_path

Computes the path to a stylesheet asset in the public stylesheets directory.

#stylesheet_url

Computes the full URL to a stylesheet asset in the public stylesheets directory.

#url_to_asset
#url_to_audio
#url_to_font
#url_to_image
#url_to_javascript
#url_to_stylesheet
#url_to_video
#video_path

Computes the path to a video asset in the public videos directory.

#video_url

Computes the full URL to a video asset in the public videos directory.

Class Attribute Details

.apply_stylesheet_media_default (rw) Also known as: #apply_stylesheet_media_default

[ GitHub ]

  
# File 'actionview/lib/action_view/helpers/asset_tag_helper.rb', line 28

mattr_accessor :apply_stylesheet_media_default

.image_decoding (rw) Also known as: #image_decoding

[ GitHub ]

  
# File 'actionview/lib/action_view/helpers/asset_tag_helper.rb', line 26

mattr_accessor :image_decoding

.image_loading (rw) Also known as: #image_loading

[ GitHub ]

  
# File 'actionview/lib/action_view/helpers/asset_tag_helper.rb', line 25

mattr_accessor :image_loading

Instance Attribute Details

#apply_stylesheet_media_default (rw)

[ GitHub ]

  
# File 'actionview/lib/action_view/helpers/asset_tag_helper.rb', line 28

mattr_accessor :apply_stylesheet_media_default

#image_decoding (rw)

[ GitHub ]

  
# File 'actionview/lib/action_view/helpers/asset_tag_helper.rb', line 26

mattr_accessor :image_decoding

#image_loading (rw)

[ GitHub ]

  
# File 'actionview/lib/action_view/helpers/asset_tag_helper.rb', line 25

mattr_accessor :image_loading

Instance Method Details

#audio_tag(*sources)

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, files that exist in your public audios directory, or Active Storage attachments.

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>

Active Storage blobs (audios that are uploaded by the users of your app):

audio_tag(user.name_pronunciation_audio)
# => <audio src="/rails/active_storage/blobs/.../name_pronunciation_audio.mp3"></audio>
[ GitHub ]

  
# File 'actionview/lib/action_view/helpers/asset_tag_helper.rb', line 593

def audio_tag(*sources)
  multiple_sources_tag_builder("audio", sources)
end

#check_for_image_tag_errors(options) (private)

[ GitHub ]

  
# File 'actionview/lib/action_view/helpers/asset_tag_helper.rb', line 634

def check_for_image_tag_errors(options)
  if options[:size] && (options[:height] || options[:width])
    raise ArgumentError, "Cannot pass a :size option with a :height or :width option"
  end
end

#extract_dimensions(size) (private)

[ GitHub ]

  
# File 'actionview/lib/action_view/helpers/asset_tag_helper.rb', line 625

def extract_dimensions(size)
  size = size.to_s
  if /\A\d(?:\.\d)?x\d(?:\.\d)?\z/.match?(size)
    size.split("x")
  elsif /\A\d(?:\.\d)?\z/.match?(size)
    [size, size]
  end
end

#image_tag(source, options = {})

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 "#{width}x#{height}" or "#{number}", so "30x45" becomes width="30" height="45", and "50" becomes width="50" 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" />
[ GitHub ]

  
# 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)

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 HTTP Early Hints, and the defer option is not enabled, Rails will push a 103 Early Hints response that links to the assets.

Options

When the last parameter is a hash you can add HTML attributes using that parameter. This includes but is not limited to the following options:

  • :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 and host 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.

  • :async - When set to true, adds the async HTML attribute, allowing the script to be fetched in parallel to be parsed and evaluated as soon as possible.

  • :defer - When set to true, adds the defer HTML attribute, which indicates to the browser that the script is meant to be executed after the document has been parsed. Additionally, prevents sending the Preload Links header.

  • :nopush - Specify if the use of server push is not desired for the script. Defaults to true.

Any other specified options will be treated as HTML attributes for the script tag.

For more information regarding how the :async and :defer options affect the <script> tag, please refer to the MDN docs.

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>

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>
[ GitHub ]

  
# 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
    ("script", "", tag_options)
  }.join("\n").html_safe

  if use_preload_links_header
    send_preload_links_header(preload_links)
  end

  sources_tags
end

#multiple_sources_tag_builder(type, sources) {|options| ... } (private)

Yields:

  • (options)
[ GitHub ]

  
# File 'actionview/lib/action_view/helpers/asset_tag_helper.rb', line 598

def multiple_sources_tag_builder(type, sources)
  options       = sources.extract_options!.symbolize_keys
  skip_pipeline = options.delete(:skip_pipeline)
  sources.flatten!

  yield options if block_given?

  if sources.size > 1
    (type, options) do
      safe_join sources.map { |source| tag("source", src: resolve_asset_source(type, source, skip_pipeline)) }
    end
  else
    options[:src] = resolve_asset_source(type, sources.first, skip_pipeline)
    (type, nil, options)
  end
end

#picture_tag(*sources, &block)

Returns an HTML picture tag for the sources. If sources is a string, a single picture tag will be returned. If sources is an array, a picture tag with nested source tags for each source will be returned. The sources can be full paths, files that exist in your public images directory, or Active Storage attachments. Since the picture tag requires an img tag, the last element you provide will be used for the img tag. For complete control over the picture tag, a block can be passed, which will populate the contents of the tag accordingly.

Options

When the last parameter is a hash you can add HTML attributes using that parameter. Apart from all the HTML supported options, the following are supported:

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 blobs (images that are uploaded by the users of your app):

picture_tag(user.profile_picture)
# => <picture><img src="/rails/active_storage/blobs/.../profile_picture.webp" /></picture>
[ GitHub ]

  
# 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)

  ("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

#resolve_asset_source(asset_type, source, skip_pipeline) (private)

[ GitHub ]

  
# File 'actionview/lib/action_view/helpers/asset_tag_helper.rb', line 615

def resolve_asset_source(asset_type, source, skip_pipeline)
  if source.is_a?(Symbol) || source.is_a?(String)
    path_to_asset(source, type: asset_type.to_sym, skip_pipeline: skip_pipeline)
  else
    polymorphic_url(source)
  end
rescue NoMethodError => e
  raise ArgumentError, "Can't resolve #{asset_type} into URL: #{e}"
end

#video_tag(*sources)

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, files that exist in your public videos directory, or Active Storage attachments.

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 the src of #image_tag.

  • :size - Supplied as "#{width}x#{height}" or "#{number}", so "30x45" becomes width="30" height="45", and "50" becomes width="50" 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>

Active Storage blobs (videos that are uploaded by the users of your app):

video_tag(user.intro_video)
# => <video src="/rails/active_storage/blobs/.../intro_video.mp4"></video>
[ GitHub ]

  
# 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