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