defining the template engine
var app = express();app.set(‘views‘‘./views‘); // 指定模板文件存放位置app.set(‘view engine‘‘jade‘) // 设置默认的模板引擎
To register the template engine with the specified extension:
app.engine(‘jade‘require(‘jade‘)._express )
Note: The _express function is a callback function provided by many template engines. However, this function only works on the default file name extension. But what if we don't use the extension of the corresponding template engine? You can no longer call the _express function. In this case we can use an alternative function, for example: The RenderFile function is provided in EJS to accomplish the same function.
Look at the following two sections of code:
‘ejs‘require(‘ejs‘)._express )
‘html‘require(‘ejs‘.renderFile) )
Once the extension is registered, the engine callback function is called to perform rendering of the template with that extension.
adding local objects
The Express () App object provides the App.locals property to store local variables, and app.locals is actually a function object, which means there are two ways to set variables.
Way One:
app.locals.title"Hello World";app.locals.version1.0;
Way two:
app.locals({title: "Hello World", version: 1.0});
render the template in the response
There are two ways to send a response template to a client:
- Express App object send;
- Response object sent;
1>, send via Express App object
Syntax format, as follows:
app.render(view, [locals], callback);
View: template file name;
[Locals]: A locals object (that is, a locals object defined in App.locals).
Callback: callback function that executes after the template is rendered. accepts two parameters. The first, err-Error object. The second one, rendereddata--the template string after rendering.
2>, Response object Send
Syntax format, as follows:
res.render(‘模板文件名(无后缀)‘);
This method renders the template directly as a response, and the results to be rendered are sent automatically in the response.
Below, take a look at the following sample code:
varExpress = require (' Express '), Jade = require (' Jade '), Ejs = require (' Ejs ');varApp = Express (); app.Set(' views ','./views '); app.Set(' view engine ',' Jade '); App.engine (' Jade ', jade._express); App.engine (' HTML ', ejs.renderfile); App.listen (8080); App.locals ({uname:' G ', vehicle:' Pandora ', Terrain:' Mountains ', Climate:' Desert ', Location:' Unknown '}); app.Get('/jade ', function(req, res) {Res.render (' User_jade ');}); App.Get('/ejs ', function(req, res) {App.render (' user_ejs.html ', function(err, Rendereddata) {Res.send (Rendereddata); });});
Using the template engine in Express