简体   繁体   English

image_tag在轨道上的红宝石

[英]image_tag in ruby on rails

I have used image_tag in ruby on rails application for two different images, and now I want to specify different CSS properties for each image. 我在ruby on rails应用程序中使用image_tag来获取两个不同的图像,现在我想为每个图像指定不同的CSS属性。 I only have one img { } tag available. 我只有一个img {}标签可用。 So, how can I do that? 那么,我该怎么做呢?

The AssetTagHelper#image_tag is defined as: AssetTagHelper#image_tag定义为:

def image_tag(source, options = {})
  options = options.symbolize_keys
  check_for_image_tag_errors(options)
  skip_pipeline = options.delete(:skip_pipeline)

  options[:src] = resolve_image_source(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]
  tag("img", options)
end

See there the options argument, if you pass a src, a srcset, width and/or options they'll be handled by the method itself, and afterwards whatever your trying to build will be passed to the helper method tag : 在此处查看options参数,如果您传递src,srcset,width和/或选项,它们将由方法本身处理,然后将您尝试构建的所有内容传递给helper方法tag

def tag(name = nil, options = nil, open = false, escape = true)
  if name.nil?
    tag_builder
  else
    "<#{name}#{tag_builder.tag_options(options, escape) if options}#{open ? ">" : " />"}".html_safe
  end
end

So, if you need to specify CSS rules, being inline or through a class then you can add them as the options in your image tag, as the tag method will add each of them within the rendered "img" HTML tag. 因此,如果需要指定CSS规则(内联或通过类),则可以将它们添加为image标记中的选项,因为tag方法会将每个规则添加到呈现的“ img” HTML标记中。

<%= image_tag 'image', class: 'class', id: 'identifier', style: 'width: 360px; height: 280px' %>

Becomes 成为

<img class="class" id="identifier" style="width: 360px; height: 280px" src="image">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM