rails 6中的asset_pack_path和image_pack_tag有什么区别?

问题描述

我认为image_pack_tag是我们在视图中使用的帮助程序,用于将图像放置在HTML表单中。但是在webpack的文档中,我也看到了asset_pack_path。现在我对此感到困惑。这里的任何人都知道确切的区别吗?

解决方法

asset_pack_path仅返回路径。 image_pack_tag返回一个包含<img> html元素的字符串。

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