Liam Emery Liam Emery - 9 months ago 20
Ruby Question

How to 'name' images in Rails?

So in html you can have the code

<img class="myimage" src="image.jpg">
which makes editing in
What is the equivalent of this when working with a

e.g where do I define the class in this
<%= image_tag "image.jpg" %>


You can still use the native HTML in a .html.erb file, exactly as you've shown. This definitely works in the ERB template:

<img class="myimage" src="image.jpg">

This will often render slightly faster than using a dynamic approach, and has the benefit of being exactly what you intend.

If you choose the dynamic tag option, you can refer to the ActionView::Helpers::AssetTagHelper reference. To get the Rails (ActionView) equivalent to what you've shown, you can use this syntax:

<%= image_tag 'image.jpg', class: 'myimage' %>

Note that the portion with the class: 'myimage' is providing the class attribute as a hash value, and this is simply shortcut syntax for { class: 'myimage' }.

You can also provide an ID to distinguish this image from other images of the same class by providing the id option, like so:

<%= image_tag 'image.jpg', class: 'myimage', id: 'image-1' %>

This will generate the following HTML:

<img src="image.jpg" class="myimage" id="image-1">

From that point, you can style the image-1 image independently of other myimage images, should you need to do so.