0

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.

3
  • 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 …? Commented 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. Commented Sep 13, 2014 at 1:37
  • 1
    Whether 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. Commented Sep 13, 2014 at 1:52

1 Answer 1

1

You need to use quotes around the value:

<script type="text/javascript" charset="utf-8">
  var url = '<%= @print_url  %>';
</script>
Sign up to request clarification or add additional context in comments.

Comments

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.