How to render a variable as html in ejs using

5/30/2024
All Articles

#nodejs node js ejs render

How to render a variable as html in ejs using

How to render a variable as html in ejs using

    Use EJS delimiters to embed the variable directly within HTML tags: <%= variable %>.
    To generate HTML conditionally dependent on the value of the variable, use conditional statements.
    To alter the variable before rendering it as HTML, use EJS filters.
    Use JavaScript functions to dynamically produce HTML and manipulate the variable.
    Use EJS partials or incorporate rendering HTML components that are reusable and contain embedded variable data.

Below is example of ejs render to html

<% var  blog=`` %>
<% articles.forEach(article => {
var url= article.slug
var tit= article.title
blog =blog+'<li class="card-title"><small><a href="/myArticles/'+url+'" class="btn btn-primary">'+tit+'</a></small></li>'  %>
<% }) %>
<div class="card mt-4">
<div class=" jumbotron card-body">
<ul>
<%- blog %>
</ul>
</div>
</div>

Conclusion

The rendering of a variable as HTML in the EJS includes a particular tage that allows us to customize the content's appearance. With this tag, the code can be executed without rendering (<% code %>), escaped (<%= code %>) and printed as HTML (<%- code %>), or rendered as HTML (<%- code %>) without escaping special characters. This tutorial will demonstrate how to render a variable as HTML in EJS using these tags in a practical way.

Article