1

@tag is a string.

Why does this work:

tag_tracker = "<%= @tag %>";
alert(tag_tracker);

But not this?

tag_tracker = <%= @tag %>; // Why is this not read as a string?
alert(tag_tracker);

Thank you in advance!

1 Answer 1

2

If you have JS inside of ERB files, you need to ensure that the javacript code that is generated is correct.

Let's assume that you have a string "div" stored in @tag

The first option:

tag_tracker = "<%= @tag %>";
alert(tag_tracker);

will generate a correct JS with div wrapped in quotes.:

tag_tracker = "div";
alert(tag_tracker);

The second one:

tag_tracker = <%= @tag %>;
alert(tag_tracker);

will generate JS without quotes around the div:

tag_tracker = div;
alert(tag_tracker);

and that is incorrect, because in this case div is interpreted as a variable, not as string.

Sign up to request clarification or add additional context in comments.

1 Comment

For strings, using <%= @tag.inspect %> outputs "div" as well.. Although inspect will work for strings, integers and arrays, it will not work for Hashes. Although .to_json will in rails apps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.