1. Intro
The Express view assistant can globally control the entire app's view variables and methods, such as the need for each template to introduce the app's name and output request address:
/view/1
App.get ("/view/1", function (request, response) {
Response.render ("View1", {
Title: "App Name",
Url:request.url,
View: "View1",
});
});
/view/2
App.get ("/view/2", function (request, response) {
Response.render ("View2", {
Title: "App Name",
Url:request.url,
View: "View2",
});
});
As above, the template variable title is a static variable, the URL is a dynamic variable, these two variables are common variables, you can extract them.
2. Static View Assistant
The static view assistant refers to the view variable, method is not related to the request, generally refers to the project name, address, such as configuration parameters or public methods, these variables, methods can only be used in the template view, if you want to use the other parts of the project public variables, methods can be under global new global variables, Method (Reference: Nodejs Learning 9:express Local, responding to global variables).
To define a static view assistant under the App object:
Define a static View assistant variable
App.locals.staticVar = "static Var";
Define a static View assistant method
App.locals.staticFn = function () {
Return "static function";
}
App.locals ({
Define a static view assistant variable 2
STATICVAR2: "Static var 2",
Define a static View Assistant Method 2
Staticfn2:function () {
Return "static function 2";
},
});
Static view variables, methods, and template variables, methods, as defined, are used as examples under the Jade template engine:
H1=staticvar
H1=STATICFN ()
H1=staticvar2
H1=STATICFN2 ()
H1=templatevar
H1=templatefn ()
3. Dynamic View Assistant
The dynamic View assistant refers to the view variable, the method is related to the request, and is generally used to parse the request information, such as user login information, request address, and so on.
To define a dynamic view assistant in the Response object:
App.use (function (request, response, next) {
Defining a dynamic View Assistant variable
Response.locals.dynamicVar = "Dynamic var";
Defining the Dynamic View Assistant method
Response.locals.dynamicFn = function () {
Return "dynamic function";
}
Response.locals ({
Define dynamic View Assistant variable 2
DYNAMICVAR2: "Dynamic var 2",
Define dynamic View Assistant Method 2
Dynamicfn2:function () {
Return "dynamic function 2";
},
});
Don't forget Next ()
Next ();
});
Defined dynamic View variables, methods, and static view variable methods, as well as template variables, methods, for example under the Jade template engine:
H1=dynamicvar
H1=DYNAMICFN ()
H1=dynamicvar2
H1=DYNAMICFN2 ()
H1=templatevar
H1=templatefn ()