如何使用Gulp将部分中的JSON和Handlebars组合成HTML?

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.jsonheaderfooter.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-sections.提前致谢!

dst*_*ley 5

第一个参数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)