How to render a variable as html in ejs using
Render a variable as HTML in EJS
EJS (Embedded JavaScript) is a popular templating engine for Node.js that allows you to generate HTML markup with JavaScript. One of its powerful features is the ability to render variables as HTML dynamically. In this article, we’ll explore how to render a variable as HTML in EJS using various techniques, including delimiters, conditional statements, filters, and reusable components.
Rendering variables as HTML in EJS is essential for:
EJS provides three types of delimiters for embedding JavaScript code:
<% code %>
: Executes JavaScript code without rendering.<%= code %>
: Renders the value of the variable with HTML escaping.<%- code %>
: Renders the value of the variable as HTML without escaping.Example:
<%- blog %>
Here, blog
is a variable containing HTML content, and it is rendered as-is without escaping special characters.
You can use conditional statements to render HTML based on the value of a variable.
Example:
<% if (user.isAdmin) { %>
<p>Welcome, Admin!</p>
<% } else { %>
<p>Welcome, User!</p>
<% } %>
EJS filters allow you to modify the value of a variable before rendering it as HTML.
Example:
<%=: user.name | capitalize %>
This filter capitalizes the user.name
before rendering it.
You can use JavaScript functions to generate HTML dynamically.
Example:
<% function generateCard(title, url) { %>
<li class="card-title">
<small><a href="<%= url %>" class="btn btn-primary"><%= title %></a></small>
</li>
<% } %>
<ul>
<% articles.forEach(article => { %>
<%= generateCard(article.title, article.slug) %>
<% }) %>
</ul>
EJS partials allow you to create reusable HTML components with embedded variables.
Example:
<%- include('partials/header', { title: 'My Blog' }) %>
Assume you have an array of articles:
const articles = [
{ title: "Introduction to EJS", slug: "intro-to-ejs" },
{ title: "Advanced EJS Techniques", slug: "advanced-ejs" }
];
Use EJS to render the articles as an HTML list:
<% let blog = ''; %>
<% articles.forEach(article => { %>
<% const url = article.slug; %>
<% const title = article.title; %>
<% blog += `<li class="card-title"><small><a href="/myArticles/${url}" class="btn btn-primary">${title}</a></small></li>`; %>
<% }) %>
<div class="card mt-4">
<div class="jumbotron card-body">
<ul>
<%- blog %>
</ul>
</div>
</div>
blog
variable is initialized as an empty string.forEach
loop iterates through the articles
array.<li>
) is created and appended to the blog
variable.blog
variable is rendered as HTML using the <%- %>
delimiter.Rendering variables as HTML in EJS is a powerful feature that enables dynamic content generation for web applications. By using EJS delimiters, conditional statements, filters, and reusable components, you can create flexible and maintainable templates. This guide has provided practical examples and best practices to help you master the art of rendering variables as HTML in EJS.