Ruben Portz
Ruben Portz

Reputation: 334

Can one place a <%= tag inside an <%= image_tag?

Can one place a <%= tag inside a <%= tag as below?

If not, what's the way do it? I've got the name of the image inside my table and want to use it in the image path when showing the image.

<%= image_tag("tools/<%= tool.logo %>", :size => "50x50", :class=> "img-circular") %>

Upvotes: 1

Views: 78

Answers (3)

Tallboy
Tallboy

Reputation: 13407

You don't want to do that because what <%= %> means in HTML is to switch to "ruby mode" (everywhere inside the brackets).

So, that means once you're in ruby mode, you can treat everything in there like your ruby IRB terminal, in which case you can just use string concatenation ("a" + "b") or interpolation ("a #{variable}").

In your case, it would just be "tools/#{tool.logo}".

Upvotes: 1

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230276

As demir hints at, inside of <%= %>, you're in ruby-land, which means you can/should write just regular ruby code. His answer solves your immediate problem, but you can sidestep it by moving the logic elsewhere. To the model, for example:

<%= image_tag(tool.logo_path, ...

Some could argue that presentation logic doesn't belong in models. In this case, you could use some flavor of a presenter pattern.

<%= image_tag(tool_presenter.logo_path, ...

Point is, views are probably not the best place for composing your asset path from pieces. They are usually complicated enough already.

Upvotes: 5

demir
demir

Reputation: 4709

In the string you can execute ruby code with #{}.

<%= image_tag("tools/#{tool.logo}", size: "50x50", class: "img-circular") %>

Upvotes: 3

Related Questions