Donato
Donato

Reputation: 2777

Ruby variable in JavaScript throws syntax error

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.

Upvotes: 0

Views: 99

Answers (1)

Gergo Erdosi
Gergo Erdosi

Reputation: 42053

You need to use quotes around the value:

<script type="text/javascript" charset="utf-8">
  var url = '<%= @print_url  %>';
</script>

Upvotes: 1

Related Questions