Suavocado
Suavocado

Reputation: 969

Interpolate variables into data attributes

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.

Upvotes: 1

Views: 553

Answers (2)

Simone Carletti
Simone Carletti

Reputation: 176402

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.

Upvotes: 2

potashin
potashin

Reputation: 44581

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 }

Upvotes: 3

Related Questions