Mathieu EUSTACHY
Mathieu EUSTACHY

Reputation: 117

Rails is escaping erb lines in a view using .html_safe

This is my first post on Stack Overflow, and not the last on my developer journey I guess.

In my Rails app, I have a problem converting html content inserted as text to actual html. It is working for html except for one line which uses erb.

View show

show.html.erb

...
<%= render 'profitability_row_element', simulation: @simulation, type: "gross" %>
...

Corresponds to the show of a simulation, we pass that said simulation as a local to our partial

Partial

_profitability_row_element.html.erb

      <p class="text-xs">
        <%= tooltip_formula(["Prix d'achat", "+", "Frais de notaire"]).html_safe %>
      </p>

To give u some context, the idea is to display some metrics with their corresponding formulas below, then when the user hovers over an element of a formula (e.g. "Prix d'achat"), it will display the value used in the calculation

Helper

simulations_helper.rb

module SimulationsHelper

  def tooltip_formula(formula_elements_array)
    formula_elements_array.map!.with_index do |formula_element, i|
      i.even? ? tooltip(formula_element) : formula_element
    end.join(' ')
  end

  def tooltip(formula_element)
    tooltip = 'class1'
    tooltiptext = 'class2'

    "<span class='#{tooltip}'>
      #{formula_element}
      <span class='#{tooltiptext}'>
        <%= simulation.#{convert_formula_element_to_corresponding_simulation_variable(formula_element)} %>
      </span>
    </span>"
  end

end

It works just fine for the html content (content #{formula_element} is correctly display and classes #{tooltip} & #{tooltiptext} are correctly applied), however it does seem to escape erb tags, I am surely doing something wrong here but I was not able to figure it out.

Result in Chrome

I would like <%= simulation.house_rent_amount_per_year %> to display its value

Any leads that would convert this erb into html ?

Thank you in advance,

Mth0158

Upvotes: 1

Views: 256

Answers (1)

alf
alf

Reputation: 18530

it does seem to escape erb tags

That happens because you're rendering HTML in a helper. Move the whole "<span ... code to the erb partial. It should look like this:

<p class="text-xs">
  <% ["Prix d'achat", "+", "Frais de notaire"].map.with_index do |formula_element, i| %>
    <% if i.even? %>
      <span...
    <% else %>
      <%= formula_element %>
    <% end %>
  <% end %>
</p>

Upvotes: 1

Related Questions