What is the difference between asset_pack_path and image_pack_tag in rails 6?
Asked Answered
Q

1

0

According to my opinion image_pack_tag is the helper that we use in the views to place the images in our HTML form. But in the documentation of webpack I see asset_pack_path also. Now I am confused about this.Anyone here knows the exact difference?

Quadrature answered 3/9, 2020 at 7:8 Comment(0)
S
3

asset_pack_path just returns the path. image_pack_tag returns a string containing a <img> html element.

module Webpacker::Helper
  ...

  # Computes the relative path for a given Webpacker asset.
  # Returns the relative path using manifest.json and passes it to path_to_asset helper.
  # This will use path_to_asset internally, so most of their behaviors will be the same.
  #
  # Example:
  #
  #   # When extract_css is false in webpacker.yml and the file is a css:
  #   <%= asset_pack_path 'calendar.css' %>  # => nil
  #
  #   # When extract_css is true in webpacker.yml or the file is not a css:
  #   <%= asset_pack_path 'calendar.css' %> # => "/packs/calendar-1016838bab065ae1e122.css"
  def asset_pack_path(name, **options)
    if current_webpacker_instance.config.extract_css? || !stylesheet?(name)
      path_to_asset(current_webpacker_instance.manifest.lookup!(name), options)
    end
  end

  # Computes the absolute path for a given Webpacker asset.
  # Returns the absolute path using manifest.json and passes it to url_to_asset helper.
  # This will use url_to_asset internally, so most of their behaviors will be the same.
  #
  # Example:
  #
  #   # When extract_css is false in webpacker.yml and the file is a css:
  #   <%= asset_pack_url 'calendar.css' %> # => nil
  #
  #   # When extract_css is true in webpacker.yml or the file is not a css:
  #   <%= asset_pack_url 'calendar.css' %> # => "http://example.com/packs/calendar-1016838bab065ae1e122.css"
  def asset_pack_url(name, **options)
    if current_webpacker_instance.config.extract_css? || !stylesheet?(name)
      url_to_asset(current_webpacker_instance.manifest.lookup!(name), options)
    end
  end

  # Creates an image tag that references the named pack file.
  #
  # Example:
  #
  #  <%= image_pack_tag 'application.png', size: '16x10', alt: 'Edit Entry' %>
  #  <img alt='Edit Entry' src='/packs/application-k344a6d59eef8632c9d1.png' width='16' height='10' />
  #
  #  <%= image_pack_tag 'picture.png', srcset: { 'picture-2x.png' => '2x' } %>
  #  <img srcset= "/packs/picture-2x-7cca48e6cae66ec07b8e.png 2x" src="/packs/picture-c38deda30895059837cf.png" >
  def image_pack_tag(name, **options)
    if options[:srcset] && !options[:srcset].is_a?(String)
      options[:srcset] = options[:srcset].map do |src_name, size|
        "#{resolve_path_to_image(src_name)} #{size}"
      end.join(", ")
    end

    image_tag(resolve_path_to_image(name), options)
  end
end
Sukey answered 3/9, 2020 at 10:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.