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

扶醉桌前 提交于 2019-11-27 17:51:55

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);
});

For convenience, registerPartials provides a quick way to load all partials from a specific directory:

var hbs = require('hbs');
hbs.registerPartials(__dirname + '/views/partials');

Partials that are loaded from a directory are named based on their filename, where spaces and hyphens are replaced with an underscore character:

template.html      -> {{> template}}
template 2.html    -> {{> template_2}}
login view.hbs     -> {{> login_view}}
template-file.html -> {{> template_file}}

Cheers!

Looks like creating a variable and pulling in the template code manually works:

var hbs = require('hbs')
  , fs = require('fs')
  , headerTemplate = fs.readFileSync(__dirname + '/views/_header.hbs', 'utf8');

and later:

hbs.registerPartial('headPartial', headerTemplate); 

For me I had template file my-partial.hbs

Then I tried to access them via:

{{> my-partial }}

But the partial was stored in hbs as my_partial regardless of the filename.

This is thanks to hbs version 3.1.0 line 218

.slice(0, -(ext.length)).replace(/[ -]/g, '_').replace('\\', '/');

This is in the readme

For me, I have a function like:

var hbs = require('hbs');
var fs = require('fs');    
var statupfunc = {
      registerHbsPartials : function(){
        //this is run when app start
        hbs.registerPartials(__dirname + "/" + resource.src.views + '/partials');        
      },
      registerOneHbsPartials : function(event){ 
        //this is run for gulp watch
        if(event.type == 'deleted')
        {
          return;
        }   
        var filename = event.path;
        var matches = /^.*\\(.+?)\.hbs$/.exec(filename);
        if (!matches) {
          return;
        }    
        var name = matches[1];    
        var template = fs.readFileSync(filename, 'utf8');    
        hbs.registerPartial(name, template);    
      }
    };

Run statupfunc.registerHbsPartials at app startup and then register gulp watch with statupfunc.registerOneHbsPartials to register partials on new creation

gulp.task('watch', function() {
    gulp.watch(resource.src.views +  '/partials/*.*', statupfunc.registerOneHbsPartials);
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!