如何在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
模板的内容.像这样:
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
推荐答案
使用escape_javascript:
Use escape_javascript:
$("#something").append("<%= escape_javascript render("post.html", post: @post) %>");
您可以render_to_string并将其转义,但是似乎并没有太多需要-而且由于它返回一个字符串,因此它将对所有标记进行HTML转义.
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
这篇关于如何在Phoenix Framework中的javascript模板中呈现html模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!