When rendering a template, you need to create template files. When creating template files, keep in mind these considerations:
Reusability: Try to make your templates reusable in other parts of you application and in other applications. Most template engines cache templates to speed up performance. The more templates you have, the more caching time your engine will have to spend. Try to organize your templates so that they can be used for multiple purposes. For example, if you have several tables of data displayed in an app, make only a single template for all of them that can not only dynamically add the data but also set column headers, titles, and such.
Size: As templates grow in size, they tend to become more and more unwieldy. Try to keep your templates compartmentalized to the type of data they are presenting. For example, if you have a template that has a menu bar, form, and table, you could split it into three separate templates.
Hierarchy: Most websites and applications are built on some sort of hierarchy. For example, the <head>
section as well as a banner and menu may be the same throughout a site. You should use a separate template for components that show up in multiple locations and just include those subtemplates when building your final page.
Listing 18.8 shows a basic EJS template that applies a set of local variables in a list to display user information. The EJS code is very basic and only uses the <%= variable %>
to pull values from the Express local variables.
01 <!DOCTYPE html>
02 <html lang="en">
03 <head>
04 <title>EJS Template</title>
05 </head>
06 <body>
07 <h1>User using EJS Template</h1>
08 <ul>
09 <li>Name: <%= uname %></li>
10 <li>Vehicle: <%= vehicle %></li>
11 <li>Terrain: <%= terrain %></li>
12 <li>Climate: <%= climate %></li>
13 <li>Location: <%= location %></li>
14 </ul>
15 </body>
16 </html>
Listing 18.9 and Listing 18.10 show how to use Jade to implement a main template and then consume it in a subtemplate. The main template in Listing 18.9 is very basic, only implementing the doctype
, html
, head
, and title
elements. It also adds the block content
element that is defined in Listing 18.10.
Notice that line 1 in Listing 18.10 extends main_jade
to include those elements first and then adds the h1
, ul
, and li
elements to get values from the local
variables.
1 doctype html
2 html(lang="en")
3 head
4 title="Jade Template"
5 body
6 block content
1 extends main_jade
2 block content
3 h1 User using Jade Template
4 ul
5 li Name: #{uname}
6 li Vehicle: #{vehicle}
7 li Terrain: #{terrain}
8 li Climate: #{climate}
9 li Location: #{location}