我正在建立一个静态网站使用车把和古普。这是我的文件夹结构:
app/
content/
intro.json
header.json
faq.json
features.json
footer.json
templates/
home.hbs
partials/
home-section.hbs
header.hbs
footer.hbs
index.html
Gulpfile.jshome.hbs的内容如下:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test</title>
</head>
<body>
{{> header}}
{{> home-section}}
{{> home-section}}
{{> home-section}}
{{> footer}}
</body>
</html>我想将intro.json、faq.json和features.json传递给每个home-section部分,header.json传递给header,footer.json传递给脚注。
到目前为止,这就是我的Gulpfile文件中的内容:
var gulp = require('gulp');
var handlebars = require('gulp-compile-handlebars');
var rename = require('gulp-rename');
gulp.task('html', function() {
return gulp.src('./app/templates/*.hbs')
.pipe(handlebars({}, {
ignorePartials: true,
batch: ['./app/templates/partials']
}))
.pipe(rename({
extname: '.html'
}))
.pipe(gulp.dest('build'));
});我还没有弄清楚如何一次传递多个JSON文件,特别是传递给home-section。
发布于 2017-01-16 03:50:41
handlebars的第一个参数是全局上下文,所有模板都可以使用。您可以将单个JSON文件加载到上下文对象中,并将其用作第一个参数。
(当然有更好的方法来做这件事,但是嘿,它既快又容易!)
var infoData = require('./app/content/info.json');
var faqData = require('./app/content/faq.json');
var featuresData = require('./app/content/features.json');然后,您可以将这些对象通过全局上下文传递给您的工具栏函数。
.pipe(handlebars({ info: infoData, faq: faqData, features: featuresData }))一旦数据在您的上下文中,您就可以这样访问它:
{{> home-section content=info }}
{{> home-section content=faq }}
{{> home-section content=features }}在您的home-section部分中,您将有一个content对象,它将包含您传递给它的文件的数据。因此,如果您的info.json文件如下所示:
{ "header": "Info", "details": "This is some information" }然后,您的home-content.hbs部分可以访问这样的数据:
<h2>{{ content.header }}</h2>
<p>{{ content.details }}</p>发布于 2017-01-16 04:29:16
不幸的是,gulp-compile-handlerbars函数只接受两个论点,第一个是传递给模板的所有数据。这意味着您必须将所有json文件一起加载,并将它们作为一个对象传递。
您可以使用一个小助手来完成这个任务,例如:
function requireJsons(fileNames) {
return fileNames.reduce(function(jsons, fileName) {
jsons[fileName] = require('app/content/' + fileNames[i] + '.json');
return jsons;
}, {});
}可用于为所有模板构建数据对象:
var data = requireJsons(['intro', 'header', 'faq', 'features', 'footer']);
gulp.task('html', function() {
return gulp.src('./app/templates/*.hbs')
.pipe(handlebars(data, {
// ...如果始终需要从app/content目录加载所有json文件,则可以使用readdirSync获取所有.json文件名,然后将它们传递给requireJsons。
var path = require('path');
var fileNames = fs.readdirSync('app/content')
.filter(function(fileName) {
return path.extname(fileName) === '.json';
});
var data = requireJsons(fileNames);当然,如果速度很重要,您可以将两者合并成一个方法,加载jsons并在一次传递中构建data对象。
另一种选择是可能单独编译每个模板,并将适当的数据传递到每个编译中。像吞咽这样的工具会有帮助。
https://stackoverflow.com/questions/41668880
复制相似问题