[英]How to render 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 render the contents of the post.html.eex
template inside the create.js.eex
template. 比方说,我有2个文件,
create.js.eex
和post.html.eex
,我想呈现的内容post.html.eex
内模板create.js.eex
模板。 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 上面的例子不起作用,因为我需要转义返回的字符串中的引号和其他东西,我找不到办法做到这一点
You can use render_to_string
您可以使用
render_to_string
Phoenix.View.render_to_string(MyApp.PageView, "index.html", foo: "bar")
Be aware that this can expose you to XSS. 请注意,这可能会使您暴露于XSS。
Use escape_javascript: 使用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. 你可以render_to_string并转义它,但似乎没有太多需要 - 因为它返回一个字符串,它将HTML转义所有标记。
Actually, this exact example is in the docs: 实际上,这个确切的例子在文档中:
https://hexdocs.pm/phoenix_html/Phoenix.HTML.html#escape_javascript/1 https://hexdocs.pm/phoenix_html/Phoenix.HTML.html#escape_javascript/1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.