📜  ejs js - Javascript (1)

📅  最后修改于: 2023-12-03 14:40:57.180000             🧑  作者: Mango

EJS - Embedded JavaScript

EJS is a popular templating language that allows developers to generate HTML pages by embedding JavaScript code within HTML markup. It is compatible with Node.js and can be used in both server-side and client-side applications.

Features
  • Simple syntax - EJS uses familiar JavaScript syntax for conditional statements, loops, and other control structures.
  • Templating support - EJS includes built-in support for template inheritance, partial views, and other advanced features.
  • Cross-platform compatibility - EJS can be used with Node.js, as well as a range of other platforms including Express, Koa, and Meteor.
  • Extensibility - EJS is highly extensible and can be easily customized with plugins and middleware.
Basic Syntax

EJS templates are simply HTML files with embedded JavaScript code.

Variables
<h1>Hello <%= name %></h1>

Variables can be referenced in EJS templates using the <%= %> syntax. In the example above, we are inserting the value of the name variable into our HTML markup.

Loops
<ul>
  <% for (var i = 0; i < items.length; i++) { %>
    <li><%= items[i] %></li>
  <% } %>
</ul>

EJS supports loops using standard JavaScript syntax. In the example above, we are iterating over an array of items and creating a list item element for each item.

Conditionals
<% if (isAdmin) { %>
  <p>Welcome, Admin!</p>
<% } else { %>
  <p>Please log in.</p>
<% } %>

EJS includes support for conditional statements using standard JavaScript syntax. In the example above, we are checking if the user is an admin and displaying a welcome message if they are, or a login prompt if they are not.

Conclusion

EJS is a powerful and flexible templating language that is widely used in web development. Its simple syntax and support for advanced features make it a great choice for both server-side and client-side applications. Whether you are building a single-page application or a complex web platform, EJS is sure to provide the flexibility and extensibility you need.