123456789 |
var app=require(
"express"
app.set(
"view engine"
,
"ejs"
);
app.get(
"/"
,
function
(req,res){
res.render(
"index"
,{
"title"
:
"test"
});
});
app.listen(3000);
|
1. Above is a basic example of express using template
App.set ("View Engine", "Ejs"); This sentence sets the template engine to Ejs (Http://github.com/visionmedia/ejs)
Ejs can be installed via NPM install Ejs
2, in the App.get.
Res.render ("index", {"title": "Test"}); will perform 2 steps.
Reads the contents of the./views/index.ejs file, and then replaces the title variable with test, for example <%=title%> changes to test. Assume that the returned content is Content1
Next, the./views/layout.ejs is read and the body variable is replaced with Content1, for example, <%=body%> becomes content1 content.
3. In 2, if you are unwilling to use the default Layout.ejs, you can specify it yourself. For example:
1 |
res.render( "index" ,{ "title" : "test" , "layout" : "main" }); |
Or
1 |
res.render( "index" ,{ "title" : "test" , "layout" : "main.ejs" }); |
4. If you are unwilling to use layout, you can set the layout to False, for example:
1 |
res.render( "index" ,{ "layout" : false }); |
5. If you do not want each request to be set individually. You can use global settings:
12345 |
app.set(
"view options"
,{
"layout"
:
false
});
|
6. Ejs, the default closing mark is <%. %>, we can also define our own tags. For example:
1234 |
app.set(
"view options"
,{
"open"
:
"{{"
,
"close"
:
"}}"
});
|
Use of Nodejs Express template (Ejs + Express)