📜  ejs - Javascript (1)

📅  最后修改于: 2023-12-03 15:00:35.010000             🧑  作者: Mango

EJS - Embedded JavaScript

Introduction

EJS (Embedded JavaScript) is a templating engine that allows developers to generate HTML markup dynamically. It is designed to simplify the process of generating HTML by using simple tags and JavaScript code to create dynamic content.

EJS is a popular choice among Node.js developers due to its ease of use and versatility. It supports a variety of features such as loops, conditionals, partials, and layout templates. Additionally, EJS is highly extensible, allowing developers to create custom filters and helpers to further streamline their development process.

Features
Simple Syntax

EJS uses simple tags to create dynamic content. The tags are as follows:

  • <% - Used to execute JavaScript code
  • <%= - Used to output the value of a JavaScript expression
  • <%- - Used to output the value of a JavaScript expression, but escapes HTML characters
Conditionals

EJS allows developers to use if-else statements in their templates. This allows for conditional rendering of HTML content based on the value of a variable.

<% if (user.isAdmin) { %>
  <a href="/admin">Admin Panel</a>
<% } else { %>
  <a href="/login">Login</a>
<% } %>
Loops

Developers can use loops such as for and foreach to iterate over arrays and objects, allowing for dynamic rendering of HTML content.

<ul>
  <% users.forEach(function(user) { %>
    <li><%= user.name %></li>
  <% }); %>
</ul>
Partial Templates

EJS allows for the creation of partial templates, which are reusable blocks of HTML code. This can greatly simplify the development process and reduce code duplication.

<h1>My Website</h1>
<%- include('partials/navigation') %>
<main>
  // Main content here
</main>
Extensibility

EJS is highly extensible, allowing developers to create custom filters and helpers to further streamline their development process. This can simplify complex logic and make code more readable.

<!-- Custom filter to convert text to uppercase -->
<%= message | uppercase %>

<!-- Custom helper to format a date -->
<p>Posted on <%= formatDate(post.date) %></p>
Conclusion

EJS is a powerful templating engine used by many Node.js developers. It offers a simple syntax, support for conditionals and loops, partial templates, and extensibility through custom filters and helpers. EJS can greatly simplify the process of generating dynamic HTML content, allowing developers to focus on their application logic rather than HTML markup.