How to render html template in javascript template in Phoenix Framework

非 Y 不嫁゛ 提交于 2020-01-13 19:25:06

问题


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

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

The example above doesn't work because I need to escape quotes and other things in the string that gets returned and I can't find a way to do it


回答1:


Use escape_javascript:

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

You can render_to_string and escape that, but there doesn't seem to be much need -- and since it returns a string, it will HTML-escape all the markup.

Actually, this exact example is in the docs:

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




回答2:


You can use render_to_string

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

Be aware that this can expose you to XSS.



来源:https://stackoverflow.com/questions/32918771/how-to-render-html-template-in-javascript-template-in-phoenix-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!