我正在使用 Handlebars 和 Gulp 构建一个静态站点。这是我的文件夹结构:
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.js
home.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
s。提前致谢!
最佳答案
handlebars
的第一个参数是您的全局上下文,可用于您的所有模板。您可以将单独的 JSON 文件加载到上下文对象中,并将其用作第一个参数。
(肯定有更好的方法来做到这一点,但嘿,它又快又容易!)
var infoData = require('./app/content/info.json');
var faqData = require('./app/content/faq.json');
var featuresData = require('./app/content/features.json');
然后,您可以通过全局上下文将这些对象传递给您的 Handlebars 功能
.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
partial 然后可以像这样访问数据:<h2>{{ content.header }}</h2>
<p>{{ content.details }}</p>
关于json - 如何使用 Gulp 将部分的 JSON 和 Handlebars 组合成 HTML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41668880/