📜  ejs 渲染 - Javascript (1)

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

EJS 渲染 - Javascript

Introduction

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.

Installation

Before using EJS, you need to install it using npm:

npm install ejs
Usage
  1. Create an EJS template file with the .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>
  1. Create a Javascript file that will render the EJS template. Require the EJS module and use its 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

EJS tags are used to embed Javascript code in your HTML markup. The following are the different types of EJS tags:

1. Output Tags

Output tags are used to print the results of a Javascript expression to the HTML output:

<p>Hello, <%= name %>!</p>
2. Scriptlet Tags

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>
<% } %>
3. Comment Tags

Comment tags are used to add comments to your EJS code. They are not included in the HTML output:

<!-- This is a comment -->
Conclusion

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.

Code Snippet

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>