📅  最后修改于: 2023-12-03 15:14:51.141000             🧑  作者: Mango
EJS (Embedded JavaScript) is a template engine that can generate HTML markup with plain Javascript. It allows you to create dynamic web pages by adding dynamic content and logic to your HTML.
In this article, we will explore the basics of EJS rendering and how to use it in your web development projects.
Before using EJS, you need to install it using npm:
npm install ejs
.ejs
extension. It can contain normal HTML code and EJS tags that start with <%
and end with %>
.<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title><%= pageTitle %></title>
</head>
<body>
<h1><%= pageTitle %></h1>
<p>This is an example of EJS rendering.</p>
</body>
</html>
render
method to render the template.const ejs = require('ejs');
const fs = require('fs');
const template = fs.readFileSync('./template.ejs', 'utf-8');
const renderedTemplate = ejs.render(template, { pageTitle: 'EJS Rendering Example' });
console.log(renderedTemplate);
In the above code, we read the contents of the template.ejs
file, and pass an object with a pageTitle
property to the render
method. The render
method replaces the EJS tags with the values from the object, and returns the rendered HTML.
EJS tags are used to embed Javascript code in your HTML markup. The following are the different types of EJS tags:
Output tags are used to print the results of a Javascript expression to the HTML output:
<p>Hello, <%= name %>!</p>
Scriptlet tags are used to execute Javascript code without printing anything to the HTML output:
<% if (isLoggedIn) { %>
<p>Welcome back!</p>
<% } else { %>
<p>Please login.</p>
<% } %>
Comment tags are used to add comments to your EJS code. They are not included in the HTML output:
<!-- This is a comment -->
EJS is a powerful tool that allows you to create dynamic web pages with plain Javascript. By using EJS tags, you can add dynamic content and logic to your HTML markup, and generate dynamic HTML in your Javascript code.
Here is a code snippet that demonstrates how to use EJS to render a template:
// Require the EJS module
const ejs = require('ejs');
const fs = require('fs');
// Read the contents of the template file
const template = fs.readFileSync('./template.ejs', 'utf-8');
// Render the template with EJS
const renderedTemplate = ejs.render(template, { pageTitle: 'EJS Rendering Example' });
// Log the rendered HTML to the console
console.log(renderedTemplate);
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title><%= pageTitle %></title>
</head>
<body>
<h1><%= pageTitle %></h1>
<p>This is an example of EJS rendering.</p>
</body>
</html>