I have a Rails controller action that initializes this variable:
@print_url = new_batch_batch_content_template_path(@batch, @content_template)
I tried to access it in an ERB template, as "Using Ruby variable in Javascript (In App View)" says I can do, so I tried:
<script type="text/javascript" charset="utf-8">
var url = <%= @print_url %>;
</script>
However, Chrome's console gives me this error:
Uncaught SyntaxError: Invalid flags supplied to RegExp constructor '13'
As you can see, it gets interpreted by JavaScript as a regular expression because it is not evaluated as a string. Why isn't Ruby evaluating this as a string? I don't understand why the example in the other link works but why mine does not.
asked Sep 12, 2014 at 23:06
Donato
2,7879 gold badges31 silver badges61 bronze badges
-
1"Why isn't ruby evaluating this as a string?" – the context of the error is not Ruby, it’s JavaScript. And how do we write text literals in JS again ...?C3roe– C3roe2014年09月12日 23:08:47 +00:00Commented Sep 12, 2014 at 23:08
-
@CBroe you are right, but at the time, I was expecting that value to be already parsed as string before it was rendered in javascript.Donato– Donato2014年09月13日 01:37:32 +00:00Commented Sep 13, 2014 at 1:37
-
1Whether or not ruby parsed it as a string doesn’t matter here – JavaScript is the context that you are introducing the value into here, and therefor you have to treat it according to the syntax rules of that context.C3roe– C3roe2014年09月13日 01:52:23 +00:00Commented Sep 13, 2014 at 1:52
1 Answer 1
You need to use quotes around the value:
<script type="text/javascript" charset="utf-8">
var url = '<%= @print_url %>';
</script>
answered Sep 12, 2014 at 23:07
Gergo Erdosi
42.3k21 gold badges122 silver badges95 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-rb