在 EJS 模板中呈现未转义 HTML
Rendering unescaped HTML in an EJS emplate
我有 mongodb 数据,我正在将它渲染到 foreach 中的 ejs 文件。
我正在渲染 articles
,架构中有一个叫做 Image 的东西。 article.Image 是这样的:
<a href="https://www.amazon.com/Sceptre-27-Inch-Gaming-Monitor-Speakers/dp/B078HSKBG3?crid=3AKNPTD0JV80A&keywords=monitors&qid=1640475680&sprefix=mo%2Caps%2C192&sr=8-3&linkCode=li3&tag=pickitly0f-20&linkId=c181027d5496b428b4a7ef54bfa654f8&language=en_US&ref_=as_li_ss_il" target="_blank"><img border="0" src="//ws-na.amazon-adsystem.com/widgets/q?_encoding=UTF8&ASIN=B078HSKBG3&Format=_SL250_&ID=AsinImage&MarketPlace=US&ServiceVersion=20070822&WS=1&tag=pickitly0f-20&language=en_US" ></a><img src="https://ir-na.amazon-adsystem.com/e/ir?t=pickitly0f-20&language=en_US&l=li3&o=1&a=B078HSKBG3" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" />
这是一个html代码块,我想在这里显示它
<div class="card-subtitle text-muted mb-2">
<%= article.Size
%>
</div>
<%= article.Image %>
<h3> <%= article.Price %> </h3>
</div>
当我 运行 代码时,我得到
这而不是显示为图像的代码。如何使数据库中呈现的 html 代码显示为图像而不是文本?
而不是 <%=
,使用 <%-
这样 EJS 就不会转义你的 HTML。
<%- article.Image %>
这里有更多信息:https://ejs.co/#docs
此外,我强烈建议 不要 在您的数据集本身中包含 HTML。总有一天,您会希望在不只是在网页上下文中的某个地方使用您的数据。将 HTML 保存在模板中,将数据(如图片 URL)保存在数据库中。
我有 mongodb 数据,我正在将它渲染到 foreach 中的 ejs 文件。
我正在渲染 articles
,架构中有一个叫做 Image 的东西。 article.Image 是这样的:
<a href="https://www.amazon.com/Sceptre-27-Inch-Gaming-Monitor-Speakers/dp/B078HSKBG3?crid=3AKNPTD0JV80A&keywords=monitors&qid=1640475680&sprefix=mo%2Caps%2C192&sr=8-3&linkCode=li3&tag=pickitly0f-20&linkId=c181027d5496b428b4a7ef54bfa654f8&language=en_US&ref_=as_li_ss_il" target="_blank"><img border="0" src="//ws-na.amazon-adsystem.com/widgets/q?_encoding=UTF8&ASIN=B078HSKBG3&Format=_SL250_&ID=AsinImage&MarketPlace=US&ServiceVersion=20070822&WS=1&tag=pickitly0f-20&language=en_US" ></a><img src="https://ir-na.amazon-adsystem.com/e/ir?t=pickitly0f-20&language=en_US&l=li3&o=1&a=B078HSKBG3" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" />
这是一个html代码块,我想在这里显示它
<div class="card-subtitle text-muted mb-2">
<%= article.Size
%>
</div>
<%= article.Image %>
<h3> <%= article.Price %> </h3>
</div>
当我 运行 代码时,我得到
而不是 <%=
,使用 <%-
这样 EJS 就不会转义你的 HTML。
<%- article.Image %>
这里有更多信息:https://ejs.co/#docs
此外,我强烈建议 不要 在您的数据集本身中包含 HTML。总有一天,您会希望在不只是在网页上下文中的某个地方使用您的数据。将 HTML 保存在模板中,将数据(如图片 URL)保存在数据库中。