简体   繁体   English

在 EJS 模板中渲染未转义的 HTML

[英]Rendering unescaped HTML in an EJS emplate

I have mongodb data, and I am rendering it to an ejs file in foreach.我有 mongodb 数据,我将它渲染到 foreach 中的 ejs 文件。

I am rendering articles , and there is something called Image in the schema.我正在渲染articles ,并且架构中有一个名为 Image 的东西。 article.Image is like this: 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;" />

It is an html code block, and I want to display it here它是一个 html 代码块,我想在这里显示它

                <div class="card-subtitle text-muted mb-2"> 
                    
                    <%= article.Size
                    %> 
                </div>
              <%= article.Image %> 
                <h3> <%= article.Price %> </h3>
            </div>

When I run the code, I get当我运行代码时,我得到这个 this instead of the code displaying as an Image.这而不是显示为图像的代码。 How do i make the rendered html code from the database show up as an image instead of text?如何使数据库中渲染的 html 代码显示为图像而不是文本?

Instead of <%= , use <%- so that EJS doesn't escape your HTML.而不是<%= ,使用<%-以便 EJS 不会逃脱您的 HTML。

<%- article.Image %>

More information here: https://ejs.co/#docs更多信息在这里: https://ejs.co/#docs

Also, I would highly recommend not including HTML in your dataset itself.另外,我强烈建议不要在数据集中包含 HTML。 There will come a day when you'll want to use your data somewhere that's not just in the context of your web page.总有一天,您会想要在不只是在 web 页面的上下文中使用您的数据。 Keep your HTML in your templates, and your data (like image URLs) in your database.将 HTML 保存在模板中,并将数据(如图像 URL)保存在数据库中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM