How to display html template in javascript template in Phoenix Framework

Let's say I have 2 files, create.js.eex and post.html.eex , and I want to display the contents of the post.html.eex template inside the create.js.eex template. Something like that:

 $("#something").append("<%= safe_to_string render "post.html", post: @post %>"); 

The above example does not work, because I need to avoid quotes and other things in the returned string, and I cannot find a way to do this

+1
source share
2 answers

Use escape_javascript:

 $("#something").append("<%= escape_javascript render("post.html", post: @post) %>"); 

You can do render_to_string and avoid it, but it doesn't seem to require much - and since it returns a string, it will supplant all HTML markup.

Actually, this exact example is given in the docs:

https://hexdocs.pm/phoenix_html/Phoenix.HTML.html#escape_javascript/1

+3
source

You can use render_to_string

  Phoenix.View.render_to_string(MyApp.PageView, "index.html", foo: "bar") 

Remember that this can lead you to XSS.

+5
source

Source: https://habr.com/ru/post/1233453/


All Articles