Express.js hbs module - register partials from .hbs file

后端 未结 6 1972
陌清茗
陌清茗 2020-12-04 16:05

I\'m using the handlebars.js hbs wrapper in express.js. I have templates working fine, but I\'m needing to add in partials to be rendered with my views.

I\'d like to

6条回答
  •  抹茶落季
    2020-12-04 16:31

    This code loads all the partial templates in a directory and makes them available by filename:

    var hbs = require('hbs');
    var fs = require('fs');
    
    var partialsDir = __dirname + '/../views/partials';
    
    var filenames = fs.readdirSync(partialsDir);
    
    filenames.forEach(function (filename) {
      var matches = /^([^.]+).hbs$/.exec(filename);
      if (!matches) {
        return;
      }
      var name = matches[1];
      var template = fs.readFileSync(partialsDir + '/' + filename, 'utf8');
      hbs.registerPartial(name, template);
    });
    

提交回复
热议问题