Question

Not sure why this line is not working

CONTROLLER

@images = {
    "Example1" => "ExampleA",
    "Example2" => "ExampleB",
}

VIEW

<% @images.each do |image, caption| %>
    <div class ="fill" style="background-image: url(<%= asset_path '#{image}.jpg' %>);">
        <div class="caption">
            <h2><%= "#{caption}" %></h2>
        </div>
    </div>
<% end %>

When I look at the output, somehow the HTML being rendered for the background image is:

<div class="fill" style="background-image: url(/#{image}.jpg);">

As general practice, my understanding is that the interpolation tags, either <% or <%=, should be as close to the Ruby code as possible (e.g, within HTML tags, or in the example of the background-image: url above)

Was it helpful?

Solution

Interpolation works with double quotes, not single quotes.

Change

style="background-image: url(<%= asset_path '#{image}.jpg' %>);"

To

style='background-image: url(<%= asset_path "#{image}.jpg" %>);'

or

style="background-image: url(<%= asset_path image %>.jpg);"

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top