Implementing a Template Engine

A growing trend is to use a template engine to generate HTML using a template file and application data rather than build HTML files from scratch or use static files. A template engine uses the template object to build HTML, based on values provided by the application. Using template engines provides two benefits:

Image Simplicity: Templates try to make it easy to generate the HTML either by a shorthand notation or by allowing JavaScript to be embedded in an HTML document directly.

Image Speed: Template engines optimize the process of building HTML documents. Many compile a template and store the compiled version in a cache that speeds up the generation of HTML responses.

The following sections discuss implementing template engines in Express. There are several template engines available for use in Express, and this chapter focuses on two: Jade and Embedded JavaScript (EJS). These two template engines work in very different ways and should give you an idea of what is available. Jade uses a shorthand notation of HTML in the template so the template files do not look like HTML. The advantage is that the template files are very small and easy to follow. The disadvantage is that you need to learn yet another language. EJS, on the other hand, uses special notation to embed JavaScript in normal HTML documents. This makes it much easier to transition from normal HTML. The downside is that the HTML documents are even more complex than the originals and not as tidy as Jade templates.

To run the examples in this section, you need to install both the jade and ejs modules in your application, using the following commands:

npm install [email protected]
npm install [email protected]

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.40.32