Bazley
Bazley

Reputation: 2847

Dynamic css classes inside embedded ruby

A Persona has persona_id of either 1, 2 or 3. I want to assign a class type of either persona-1-button, persona-2-button or persona-3-button inside the embedded ruby. The following code is not working and I don't know why:

<% current_user.personas.each do |persona| %>
  <% foo = persona.persona_id.to_s %>
  <% bar = "persona-" + foo + "-button" %>
  <%= link_to "Persona", persona_path(persona), class: "btn btn-medium bar" %>
<% end %>

I didn't do it the follwoing way because it seems you can't have a <%=%> inside a <%=%>:

<% current_user.personas.each do |persona| %>
  <%= link_to "Persona", persona_path(persona), class: "btn btn-medium persona<%=persona.persona_id%>button" %>
<% end %>

Upvotes: 0

Views: 728

Answers (2)

Jakob S
Jakob S

Reputation: 20125

You have it almost correct already.

The thing you need to realise is that when you're inside the <%/%> tags, you're in a Ruby context. That means, that the "..." creates a String inside which you can use regular Ruby string interpolation, like this:

  <%= link_to "Persona", persona_path(persona), class: "btn btn-medium #{bar}" %>

Upvotes: 4

D-side
D-side

Reputation: 9485

You're placing a variable in Ruby context where you are bound by the rules of Ruby, not ERB. And in Ruby it's done using string interpolation:

<%= link_to "Persona", persona_path(persona), class: "btn btn-medium #{bar}" %>

Upvotes: 3

Related Questions