Notes on Handlebars Template Inheritance for Express Beginners


templatessucceed, The same disc, Different colors~

  • replenish Notes for Express Beginners on Dynamically Rendering HTML, Previous articleOnly a preliminary realizationhtml The dynamic rendering of, But not flexible enough., If writing a dynamic website, Will encounter a large number of templates Scenarios for reuse, for eachurl Write a separatehtml documents It's very time-consuming and labor-intensive, And the maintainability is not good, Handlebars( hereinafter referred to ashbs) Provides us with the inheritance templates( resembledjango ofextend) harmony Insert code block( resembledjango ofinclude) promotion of the method, I'll do a demo below

templates Succession of layouts

The site has multiple pages, the layout of the pages are more or less the same, the header and footer may be common, we can set a default layout for all pages

 // Configure the template engine, set the default template layout
app.engine('html', exphbs({
    layoutsDir: "views/layouts/",
    defaultLayout: 'layout-header-footer.html',
    extname: '.html'
}));
 // The page corresponding to the root route, with the default template layout enabled
app.get('/', function(req, res) {
    res.render('index', {
        title: " front page",
        personInfoList: [{
            name: " fig. big shot( One Punch Superman)",
            age: 20
        }, {
            name: " gunslinger( Misaka Mikoto)",
            age: 15
        }]
    });
});

Create a new layouts folder in the views folder,create a new layouts folder in thelayout-header-footer.html act as templates ,inlayout-header-footer.html Write the following code inside:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{title}}</title>
</head>
<body>

    <style>
        body{
            margin: 0;
            padding: 0;
        }
    </style>
    <header style="width: 100%; height: 80px; text-align: center; line-height: 80px; background-color: #44A1F8; color: #ffffff;"> This is the head.</header>
    {{{body}}}
    <footer style="position: fixed; bottom:0;  width: 100%; height: 80px; text-align: center; line-height: 80px; background-color: #64B587; color: #ffffff;"> This is the bottom.</footer>
</body>
</html>

willviews folder, index.html is streamlined (only key content is retained)body)

<h1 style="color: #64B587"> profile</h1>
{{#each personInfoList}}
    <h2> nicknames:{{this.name}}</h2>
    <h2> age:{{this.age}}</h2>
    <hr>
{{/each}}
  • revisit interviews roots routing (in computer networks)

Some pages may be more specific and only need to display the generic bottom

  • In the layouts folder, create a newlayout-footer.html As a template (as the name implies, the same as the generic template above, layout-header-footer.html Compared to, layout-footer.html Only the bottom content), layout-footer.html The contents inside are:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{title}}</title>
</head>
<body>
    <style>
        body{
            margin: 0;
            padding: 0;
        }
    </style>
    {{{body}}}
    <footer style="position: fixed; bottom:0;  width: 100%; height: 80px; text-align: center; line-height: 80px; background-color: #64B587; color: #ffffff;"> Only the bottom</footer>
</body>
</html>

  • prepare/about path handler, let/about Corresponding web sleeveslayout-footer.html templates
// match/about routing (in computer networks)
app.get('/about', function(req, res) {
    res.render('about', {
        layout: "layout-footer.html"
    });
});
  • Under views, writeabout.html documents
<h1> with respect to</h1>

  • interviewshttp://localhost:3000/about , the effect is shown in the picture

Above, we have achieved default templates disposition harmony Personalized template layout of prepare harmony use, however (located) at In actual development, I might meet (located) at Within a page, Introduction of code blocks demand for, For example, inserting ad space! Let's complete the example of introducing ad space below~

Introduction of code blocks

Request: Introduce advertising space

  • (located) atviews Folder Newpartials Folder, inpartials New construction withinad.html ,inad.html inner prepare Ad Code

<div style="width: 100%; height: 20px; text-align: center; font-size: 12px; line-height: 20px; color: #413F43; background-color: #F0BB40;"> Here's a commercial.</div>
  • Configure in express-simple-server.js The directory where the ad code is located

 // Configuring the template engine
app.engine('html', exphbs({
+   partialsDir: 'views/partials/',
    layoutsDir: "views/layouts/",
    defaultLayout: 'layout-header-footer.html',
    extname: '.html'
}));
  • Modify abou.html to insert ad code

<h1> with respect to</h1>
{{>ad}}
  • View the insertion effect

  • express-simple-server.js final code
const express = require('express');
const exphbs = require('express-handlebars');
const app = express();

 // Configuring the template engine
app.engine('html', exphbs({
    partialsDir: 'views/partials/',
    layoutsDir: "views/layouts/",
    defaultLayout: 'layout-header-footer.html',
    extname: '.html'
}));
app.set('view engine', 'html');


 // If a port is set in the environment variable, use the port number set in the environment variable, otherwise use port 3000
app.set('port', process.env.PORT || 3000);


 // Match static file directories
app.use(express.static(__dirname + '/public'));

 // match root route / (if no specific status code is returned, then 200 is returned by default)
app.get('/', function(req, res) {
    res.render('index', {
        title: " front page",
        personInfoList: [{
            name: " fig. big shot( One Punch Superman)",
            age: 20
        }, {
            name: " gunslinger( Misaka Mikoto)",
            age: 15
        }]
    });
});

// match/about routing (in computer networks)
app.get('/about', function(req, res) {
    res.render('about', {
        layout: "layout-footer.html"
    });
});


 // Custom 404 page (returns 404 status code)
app.use(function(req, res) {
    let currentTime = new Date();
    res.type('text/plain');
    res.status(404);
    res.send('404 -  you interviews The page may have gone to Mars.
' + currentTime);
});


 // Custom 500 page (returns 500 status code)
app.use(function(err, req, res, next) {
    let currentTime = new Date();
    let errInfo = err.stack;
    res.type('text/plain');
    res.status(500);
    res.send('500 -  An error occurred on the server
' + 'errInfo:' + errInfo + '
' + 'currentTime:' + currentTime);
});


 // Listen to the service port to ensure that the program does not exit
app.listen(app.get('port'), function() {
    console.log('Express  services are being (located) at movement (located) at http://localhost:' + app.get('port') + ';  press Ctrl-C  Shutting down services.');
})

Summary:

If you understand django's template inheritance (extend) and code insertion (include) rules, you will find that hbs is also similar, in fact, hbs there is a play called helper, can be more flexible insert css, js, html, interested in understanding yourself, or wait for my subsequent updates


Recommended>>
1、1Introduction to Driver Concepts
2、Understanding SpatialTransformerNetworks
3、LeetCodeWeeklyContest88 848 letter shift
4、Learn FrontEnd Modular Development in 30 Minutes
5、From AdaBoost to GBDT part2

    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号