Visual Studio Code Creates Node.js+Express+handlebars Project-Handlebars Page Template

Keywords: Handlebars npm Session JSON

The page rendering template created with Express is jade Yes, I'd like to introduce you now. handlebarsjs Why don't I use this by default?
The reason you know when you use it, jade is very powerful, but the grammar it uses is unfamiliar to many people. Project development, bug s, style problems are difficult to solve. Of course, another reason is that I like the way of thinking of MVC. This handlebars JS is very handy for me.

First step
Installation, you can directly install hbs This
One is the middleware of Express and handlebars js, which is the platform for their interaction. The grammar is the same as handlebars js.

npm install hbs

If you don't see what npm means in the previous chapter.

The second step

Let's configure this template:
In app.js

app.set('view engine', 'hbs');

If you don't want the template to be the end of hbs, you can change it to

app.set('view engine', 'html');
app.engine('html', require('hbs').__express);

The third step
Template Page, Error Page, Ordinary Page
1. This is the template page.

2. This is a common page using template pages.

3. Interface effect

Advanced
You don't have to look at it as soon as you touch it.

var hbs = require('hbs');
var session = require('express-session');
var blocks = {};

hbs.registerHelper('extend', function(name, context) {
    var block = blocks[name];
    if (!block) {
        block = blocks[name] = [];
    }

    block.push(context.fn(this)); // for older versions of handlebars, use block.push(context(this));
});

hbs.registerHelper('block', function(name) {
    var val = (blocks[name] || []).join('\n');

    // clear the block
    blocks[name] = [];
    return val;
});

//Judging Equivalence
hbs.registerHelper('compare', function(left, operator, right, options) {
    if (arguments.length < 3) {
        throw new Error('Handlerbars Helper "compare" needs 2 parameters');
    }
    var operators = {
        '==':     function(l, r) {return l == r; },
        '===':    function(l, r) {return l === r; },
        '!=':     function(l, r) {return l != r; },
        '!==':    function(l, r) {return l !== r; },
        '<':      function(l, r) {return l < r; },
        '>':      function(l, r) {return l > r; },
        '<=':     function(l, r) {return l <= r; },
        '>=':     function(l, r) {return l >= r; },
        'typeof': function(l, r) {return typeof l == r; }
    };

    if (!operators[operator]) {
        throw new Error('Handlerbars Helper "compare" doesn\'t know the operator ' + operator);
    }

    var result = operators[operator](left, right);

    if (result) {
        return options.fn(this);
    } else {
        return options.inverse(this);
    }
});

//Date conversion
hbs.registerHelper("prettifyDate", function(timestamp) {
    if(timestamp==''|| timestamp==undefined)
        return''
    else
        return (new Date(timestamp)).format("yyyy-MM-dd");
});

hbs.registerPartials(__dirname + '/views/partials');
hbs.registerHelper('objectToJson', function(context, options) {
    var rtn=JSON.stringify(context)
    return rtn;
});


// Extension of Date to convert Date to String in a specified format
// Month (M), day (d), hour (h), minute (m), second (s), quarter (q) can use 1-2 placeholders.
// Year (y) can use 1 - 4 placeholders, millisecond (S) can only use 1 placeholder (1 - 3 digits)
Date.prototype.format = function(fmt)
{
    var o = {
        "M+" : this.getMonth()+1,                 //Month
        "d+" : this.getDate(),                    //day
        "h+" : this.getHours(),                   //hour
        "m+" : this.getMinutes(),                 //branch
        "s+" : this.getSeconds(),                 //second
        "q+" : Math.floor((this.getMonth()+3)/3), //quarter
        "S"  : this.getMilliseconds()             //Millisecond
    };
    if(/(y+)/.test(fmt))
        fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
    for(var k in o)
        if(new RegExp("("+ k +")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
    return fmt;
}

//Determine whether an array or object is empty
__isEmprtyObj =function(obj){
    var name;
    for ( name in obj ) {
        return false;
    }
    return true;
};

//IE version is incompatible
if (!Array.indexOf) {
      Array.prototype.indexOf = function (obj) {
              for (var i = 0; i < this.length; i++) {
                      if (this[i] == obj) {
                             return i;
                          }
              }
            return -1;
    }
 }


//Thousand bit
hbs.registerHelper("thousandths", function(num) {
    if(num==''|| num==undefined)
        return''
    else
        return (num.toFixed(0) + '').replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, '$&,');
});

Welcome to join the group to exchange!
315552185

Posted by poring on Thu, 14 Feb 2019 16:18:19 -0800