Home > Web Front-end > JS Tutorial > Using the template engine in Express_javascript tips

Using the template engine in Express_javascript tips

WBOY
Release: 2016-05-16 15:26:29
Original
1131 people have browsed it

You need to make the following settings in your application to allow Express to render template files:

views, the directory where template files are placed, for example: app.set('views', './views')
view engine, template engine, such as: app.set('view engine', 'jade')

Then install the corresponding template engine npm package.

$ npm install jade --save
Copy after login

A template engine compatible with Express, such as Jade, renders the template by calling its exported method __express(filePath, options, callback) via res.render().

Some template engines do not follow this convention. Consolidate.js can map all popular template engines in Node to this convention, so that it can be seamlessly connected with Express.

Once the view engine is set up successfully, there is no need to explicitly specify the engine, or load the template engine module in the application, Express is already loaded internally, as shown below.

app.set('view engine', 'jade');
Copy after login

Generate a Jade template file named index.jade in the views directory with the following content:

html
 head
  title!= title
 body
  h1!= message
Copy after login

Then create a route rendering index.jade file. If the view engine is not set, you need to specify the view file suffix, otherwise it will be missed.

app.get('/', function (req, res) {
 res.render('index', { title: 'Hey', message: 'Hello there!'});
});
Copy after login

Send a request to the homepage at this time, and "index.jade" will be rendered as HTML.

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template