Using the template engine in Express _javascript tips

Source: Internet
Author: User

The following settings are required in the application to allow Express rendering template files:

Views, put the directory of template files, such as: app.set (' views ', './views ')
View engine, template engine, such as: App.set (' View engine ', ' Jade ')

Then install the appropriate template engine NPM package.

$ NPM Install Jade--save

And the Express-compatible template engine, such as Jade, invokes its export method __express (FilePath, Options, callback) rendering template via Res.render ().

Some template engines do not follow this convention, and Consolidate.js can map all the popular template engines in the Node to this Convention, which seamlessly connects to Express.

Once the view engine is set successfully, you do not need to explicitly specify the engine or load the template engine module in the application, and Express is already loaded internally, as shown below.

App.set (' View engine ', ' Jade ');

Generate the Jade template file named Index.jade in the views directory as follows:

HTML
 head
  title!= title
  h1!= Message

Then create a route rendering Index.jade file. If you do not set view engine, you need to indicate the suffix of the view file, otherwise it will be omitted.

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

At this point, the request is sent to the home page, and "Index.jade" is rendered as HTML.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.