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

Using the template engine in Express_javascript tips

WBOY
WBOYOriginal
2016-05-16 15:26:291042browse

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

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');

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

html
 head
  title!= title
 body
  h1!= message

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!'});
});

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

Statement:
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