Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Rendering unescaped HTML in an EJS emplate

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%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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

                <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
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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading