Sending data from Phoenix to JavaScript

I am trying to send data from Phoenix to Javascript in a template and have this code in the template:

var render_asciidoc = function() {
   var content = "<%= Phoenix.HTML.raw @document.rendered_content %>";

However, JS is not interpreting the string = value of @document.rendered_content
as I would like it to – see this console message which comes from the resulting error:

var render_asciidoc = function() {
            var content = "----
>>> Test
----

$a^2 + b^2 = c^2$

";

NOTE. the string @document.rendered_content is

----
>>> Test
----

$a^2 + b^2 = c^2$

JavaScript doesn’t have multiline strings. Use escape_javascript/1.

var content = "<%= raw(escape_javascript(@document.rendered_content)) %>";

In JavaScript, you can use template literals for multiline strings, but since you’re interpolating via eex you should escape it.

4 Likes

Yep. You are almost there. @net has your answer. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

1 Like

Thankyou @net – all working now!

Thanks @net!