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. I only have one img { } tag available. So, how can I do that?
The AssetTagHelper#image_tag
is defined as:
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
:
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.
<%= 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">
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.