Interpolate variables into data attributes

553 views Asked by At

This is how I usually create a link with data.

= link_to 'link name', link_path, data: { day: '1' }

but now I need the "1" to be replaced with a rails variable like this.

= link_to 'link name', link_path, data: { day: '#{customer.info}' }

but It doesn't work and I'm not sure how to go about it.

2

There are 2 answers

0
Simone Carletti On BEST ANSWER

If you are already in a Ruby context, just use the variable.

= link_to 'link name', link_path, data: { day: customer.info }

What your existing code is doing is passing a string with ruby code inside. The code will not be evaluated because wrapped by single quotes.

In order to use interpolation, you must use double quotes.

= link_to 'link name', link_path, data: { day: "#{customer.info}" }

However, as I mentioned at the begin of the answer, you don't need to interpolate the value since here.

1
potashin On

You can interpolate variables into strings created only with double quotes ":

= link_to 'link name', link_path, data: { day: "#{customer.info}" }

By the way, the following seems just enough:

= link_to 'link name', link_path, data: { day: customer.info }