Rendering Templates in a Response

Once you have a template engine defined and configured and have created your templates, you can send a rendered template by using the Express app object or using the Response object. To render a template in the Express app object, you use the app.render() method, shown below:

app.render(view, [locals], callback)

The view parameter specifies the view filename in the views directory. If no extension is included on the file, the default extensions, such as .jade and .ejs, are tried. The locals parameter allows you to pass in a locals object if one has not been defined in app.locals already. The callback function is executed after the template has been rendered and should accept an error object for the first parameter and the string form of the rendered template as the second.

To render a template directly into a response, you can use the res.render() function, which works exactly the same as app.render() except that no callback is needed. The rendered results are automatically sent in the response.

The app.render() and res.render() methods both work well. If you do not need to do anything with the data before sending it, you can use the res.render() method to avoid the extra code you need in order to call res.send() to send the data.

Listing 18.11 puts all the template rendering concepts together in a couple of basic examples. Lines 5–8 set up the views directory and view engine and register jade and ejs. Then lines 10–16 define user information in the app.locals function.

Lines 17–19 handle the /jade route, which directly renders the user_jade.jade template from Listing 18.10 with the defined locals in the client response.

Lines 20–24 handle the /ejs route by first calling app.render() to render the users_ejs.html template defined in Listing 18.8 into the string renderedData. Then the res.send() command sends that data. Figure 18.6 shows the rendered webpages from both functions.

Listing 18.11 express_templates.js: Implementing Jade and EJS templates in Express


01 var express = require('express'),
02     jade = require('jade'),
03     ejs = require('ejs'),
04 var app = express();
05 app.set('views', './views'),
06 app.set('view engine', 'jade'),
07 app.engine('jade', jade.__express);
08 app.engine('html', ejs.renderFile);
09 app.listen(80);
10 app.locals.uname = "Brad";
11 app.locals.vehicle = "Jeep";
12 app.locals.terrain = "Mountains";
13 app.locals.climate = "Desert";
14 app.locals.location = "Unknown";
15 app.get('/jade', function (req, res) {
16   res.render('user_jade'),
17 });
18 app.get('/ejs', function (req, res) {
19   app.render('user_ejs.html', function(err, renderedData){
20     res.send(renderedData);
21   });
22 });


Image

Figure 18.6 Webpages generated by rendering Jade and EJS templates.

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

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