Home > Net >  Rendering unescaped HTML in an EJS emplate
Rendering unescaped HTML in an EJS emplate

Time:12-26

I have mongodb data, and I am rendering it to an ejs file in foreach.

I am rendering articles, and there is something called Image in the schema. article.Image is like this:

<a href="https://www.amazon.com/Sceptre-27-Inch-Gaming-Monitor-Speakers/dp/B078HSKBG3?crid=3AKNPTD0JV80A&keywords=monitors&qid=1640475680&sprefix=mo,aps,192&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

                <div > 
                    
                    <%= article.Size
                    %> 
                </div>
              <%= article.Image %> 
                <h3> <%= article.Price %> </h3>
            </div>

When I run the code, I get this 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?

CodePudding user response:

Instead of <%=, use <%- so that EJS doesn't escape your HTML.

<%- article.Image %>

More information here: https://ejs.co/#docs

Also, I would highly recommend not including HTML in your dataset itself. 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. Keep your HTML in your templates, and your data (like image URLs) in your database.

  • Related