假设我有2个文件create.js.eex
和post.html.eex
,我想在post.html.eex
模板中呈现create.js.eex
模板的内容。像这样:
$("#something").append("<%= safe_to_string render "post.html", post: @post %>");
上面的示例不起作用,因为我需要转义返回的字符串中的引号和其他内容,我找不到方法来执行此操作
答案 0 :(得分:6)
您可以使用render_to_string
Phoenix.View.render_to_string(MyApp.PageView, "index.html", foo: "bar")
请注意,这可能会使您暴露于XSS。
答案 1 :(得分:4)
使用escape_javascript:
$("#something").append("<%= escape_javascript render("post.html", post: @post) %>");
你可以使用render_to_string并转义它,但似乎没有太多需要 - 因为它返回一个字符串,它将HTML转义所有标记。
实际上,这个确切的例子在文档中:
https://hexdocs.pm/phoenix_html/Phoenix.HTML.html#escape_javascript/1