node.js Express.js hbs 模块 - 从 .hbs 文件注册部分

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8059914/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:45:07  来源:igfitidea点击:

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

node.jsexpresshandlebars.js

提问by swatkins

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

我在express.js 中使用 handlebars.js hbs 包装器。我的模板工作正常,但我需要添加要使用我的视图呈现的部分。

I'd like to do something like this:

我想做这样的事情:

hbs.registerPartial('headPartial', 'header'); 
// where "header" is an .hbs file in my views folder

However, it's throwing a "header partial can not be found".

但是,它抛出“找不到标题部分”。

I can make the registerPartial work if I pass a string of html to the second param, but I'd like to use separate view files for my partials.

如果我将一串 html 传递给第二个参数,我可以使 registerPartial 工作,但我想为我的部分使用单独的视图文件。

I haven't found any documentation on this, but hoping I may just be missing something easy.

我还没有找到任何关于此的文档,但希望我可能只是遗漏了一些简单的东西。

Does anyone know how to use view files in the registerPartial method? If so, how do I implement this?

有谁知道如何在 registerPartial 方法中使用视图文件?如果是这样,我该如何实施?

UPDATE

更新

To give more context, let me add more code. Here is my "server" file - app.js

为了提供更多上下文,让我添加更多代码。这是我的“服务器”文件 - app.js

var express = require('express')
, routes = require('./routes')
, hbs = require('hbs');

var app = module.exports = express.createServer();

// Configuration

app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'hbs');
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function(){
  app.use(express.errorHandler());
});

// this is the line that generates the error
hbs.registerPartial('headPartial', 'header'); 

// What I'm expecting is for "headPartial" to be a compiled template partial 
// of the template within views/header.hbs, but it is not loading this way.
// If I do something like hbs.registerPartial('headPartial', '<p>test</p>');
// then it does work. I need to know how to pass an .hbs file to the
// registerPartial method.

// Routes
app.get('/', routes.index);

app.listen(3000);

And here is my routes.index file:

这是我的 routes.index 文件:

exports.index = function(req, res){
  res.render('index', { title: 'Express' })
};

In my views folder, I have three templates:

在我的视图文件夹中,我有三个模板:

views/
  header.hbs (this is my partial)
  index.hbs
  layout.hbs

In my index.hbs file, I'm calling the 'headPartial' partial with:

在我的 index.hbs 文件中,我调用了“headPartial”部分:

{{> headPartial}}

Any help is greatly appreciated.

任何帮助是极大的赞赏。

回答by Ben Williamson

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

回答by milyord

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

为方便起见, registerPartials 提供了一种从特定目录加载所有部分的快速方法:

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!

干杯!

回答by swatkins

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

回答by Dan Baker

For me I had template file my-partial.hbs

对我来说,我有模板文件 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.

但是无论文件名如何,部分都作为 my_partial 存储在 hbs 中。

This is thanks to hbs version 3.1.0 line 218

这要归功于 hbs version 3.1.0 line 218

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

This is in the readme

这是在自述文件中

回答by Hoàng Ngh?a

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.registerHbsPartialsat app startup and then register gulp watch with statupfunc.registerOneHbsPartialsto register partials on new creation

在应用程序启动时运行statupfunc.registerHbsPartials,然后使用statupfunc.registerOneHbsPartials注册gulp watch以在新创建时注册部分

gulp.task('watch', function() {
    gulp.watch(resource.src.views +  '/partials/*.*', statupfunc.registerOneHbsPartials);
});