How to render a variable as html in ejs using

5/30/2024

Render a variable as HTML in EJS

Go Back

How to Render a Variable as HTML in EJS: A Comprehensive Guide with Examples

Render a variable as HTML in EJS

Introduction

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.

Why Render Variables as HTML in EJS?

Rendering variables as HTML in EJS is essential for:

  • Dynamic Content: Displaying data-driven content on web pages.
  • Reusable Components: Creating modular and reusable HTML components.
  • Conditional Rendering: Generating HTML based on specific conditions.
  • Customization: Tailoring the appearance of content dynamically.

Key Techniques to Render Variables as HTML in EJS

1. Using EJS Delimiters

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.

2. Conditional Rendering

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

3. Using EJS Filters

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.

4. Dynamic HTML Generation with JavaScript Functions

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>
    

5. Using EJS Partials for Reusable Components

EJS partials allow you to create reusable HTML components with embedded variables.

Example:


<%- include('partials/header', { title: 'My Blog' }) %>
    

Practical Example: Rendering a Blog List

Step 1: Define the Data

Assume you have an array of articles:


const articles = [
    { title: "Introduction to EJS", slug: "intro-to-ejs" },
    { title: "Advanced EJS Techniques", slug: "advanced-ejs" }
];
    

Step 2: Render the Data as HTML

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>
    

Explanation of the Code

  1. Variable Initialization: The blog variable is initialized as an empty string.
  2. Loop Through Articles: The forEach loop iterates through the articles array.
  3. Dynamic HTML Generation: For each article, a list item (<li>) is created and appended to the blog variable.
  4. Render HTML: The blog variable is rendered as HTML using the <%- %> delimiter.

Best Practices for Rendering Variables as HTML in EJS

  1. Sanitize Input: Always sanitize user-generated content to prevent XSS attacks.
  2. Use Partials: Break down complex templates into reusable partials for better maintainability.
  3. Optimize Performance: Minimize the use of inline JavaScript for better performance.
  4. Leverage Filters: Use EJS filters to transform data before rendering.

Conclusion

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.