Cas*_*ams 6 json handlebars.js gulp gulp-compile-handlebars
我正在使用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
Run Code Online (Sandbox Code Playgroud)
home.hbs的内容是这样的:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test</title>
</head>
<body>
{{> header}}
{{> home-section}}
{{> home-section}}
{{> home-section}}
{{> footer}}
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
我想在传递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'));
});
Run Code Online (Sandbox Code Playgroud)
我一直无法弄清楚如何传递多个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');
Run Code Online (Sandbox Code Playgroud)
然后,您可以通过全局上下文将这些对象传递给您的车把函数
.pipe(handlebars({ info: infoData, faq: faqData, features: featuresData }))
Run Code Online (Sandbox Code Playgroud)
一旦数据位于您的上下文中,您就可以像这样访问它:
{{> home-section content=info }}
{{> home-section content=faq }}
{{> home-section content=features }}
Run Code Online (Sandbox Code Playgroud)
在您的home-section
部分中,您将有一个content
对象,其中包含您传递到其中的文件的数据。因此,如果您的info.json
文件如下所示:
{ "header": "Info", "details": "This is some information" }
Run Code Online (Sandbox Code Playgroud)
然后,您的home-content.hbs
部分可以像这样访问数据:
<h2>{{ content.header }}</h2>
<p>{{ content.details }}</p>
Run Code Online (Sandbox Code Playgroud)