gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 22:33:49 27 4
gpt4 key购买 nike

我正在使用handlebars.js hbs wrapperexpress.js 。我的模板工作正常,但我需要添加部分内容才能使用我的 View 进行渲染。

我想做这样的事情:

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

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

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

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

有人知道如何在registerPartial方法中使用 View 文件吗?如果是这样,我该如何实现?

更新

为了提供更多上下文,让我添加更多代码。这是我的“服务器”文件 - 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);

这是我的routes.index 文件:

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

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

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

在我的index.hbs 文件中,我使用以下方式调用“headPartial”部分:

{{> headPartial}}

非常感谢任何帮助。

最佳答案

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

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

从目录加载的部分根据其文件名命名,其中空格和连字符替换为下划线字符:

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

干杯!

关于node.js - Express.js hbs 模块 - 从 .hbs 文件注册部分内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32863137/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com