Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is String Interpolation Failing in erb Template?

I have the following code in a .erb file:

<% embed='<a href="http://someurl.com/whatever">#{@webcast.name}</a>'%>

<p id="embedCode">
    <pre>
        <code>
            <%= embed %>
        </code>
    </pre>
</p>

The anchor tag is correctly displayed onscreen as text rather than rendered as a dom element, however the string interpolation is failing. The html is successfully displayed as text but #{@webcast.name} is not evaluated. If a include <%= @webcast.name => in the template, the webcast name in rendered successfully.

like image 881
Undistraction Avatar asked May 18 '12 09:05

Undistraction


People also ask

What is string interpolation in Ruby?

String Interpolation refers to substitution of defined variables or expressions in a given String with respected values. This is how, string Interpolation works, it executes whatever that is executable. Let's see how to execute numbers and strings. Syntax: #{variable}

Does RuboCop format ERB?

Rubocop. Runs RuboCop on all ruby statements found in ERB templates. The RuboCop configuration that erb-lint uses can inherit from the configuration that the rest of your application uses.

What does ERB do in Ruby?

ERB (or Ruby code generated by ERB ) returns a string in the same character encoding as the input string. When the input string has a magic comment, however, it returns a string in the encoding specified by the magic comment.

What is ERB templating?

An ERB template looks like a plain-text document interspersed with tags containing Ruby code. When evaluated, this tagged code can modify text in the template. Puppet passes data to templates via special objects and variables, which you can use in the tagged Ruby code to control the templates' output.


1 Answers

Because strings delimited with single quotation marks '' are not interpolated.

Change your code to e.g.:

<% embed = "<a href=\"http://someurl.com/whatever\">#{@webcast.name}</a>" %>

or (if you want to avoid masking the double-quote characters ")

<% embed = %(<a href="http://someurl.com/whatever">#{@webcast.name}</a>) %>

or just (thanks to Samy Dindane for the hint):

<% embed = "<a href='http://someurl.com/whatever'>#{@webcast.name}</a>" %>
like image 108
undur_gongor Avatar answered Sep 18 '22 06:09

undur_gongor