📌  相关文章
📜  express view engine', 'ejs - Javascript (1)

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

Express View Engine - EJS

Express is a popular web framework for Node.js, which provides a lot of features and templates for developing server-side applications, and EJS is one of the popular template engines used in Express.

What is EJS?

EJS stands for Embedded JavaScript and is a simple templating language that lets you generate HTML markup with plain JavaScript. EJS allows you to define templates that contain placeholders, which you can then fill in with dynamic data from your application. It provides a way to include data in your views dynamically and render them on the client-side.

Advantages of EJS
  • EJS uses plain JavaScript syntax for writing templates, making it easy to learn and use for developers already familiar with JavaScript.
  • It allows you to generate dynamic HTML content quickly and easily.
  • It has support for conditional statements, loops, and other programming features.
  • It allows you to pass data from your server to your client-side views, making it easy to build dynamic web pages.
  • EJS comes with Express.js by default, so there is no need to install any additional dependencies.
How to use EJS with Express

To use EJS with Express, you need to install the EJS module and configure it with your express application:

Install EJS
npm install ejs
Configure EJS
const express = require('express');
const app = express();

// set the view engine to ejs
app.set('view engine', 'ejs');

// set the views directory
app.set('views', __dirname + '/views');
Render EJS views with Data
// create a simple route that renders an EJS view
app.get('/hello', function(req, res) {
  res.render('hello', { name: 'John' });
});

// create an EJS view file: hello.ejs
<p>Hello <%= name %>!</p>
Conclusion

EJS is a powerful and easy-to-use template engine that allows you to generate dynamic HTML content with plain JavaScript. When used with Express, it provides a simple and efficient way to build dynamic web pages.