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

标签 json gulp handlebars.js 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

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.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'));
});

我一直无法弄清楚如何一次传递多个 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/

相关文章:

ios - 如何访问在我的应用程序中的函数中创建的 json 数组?

node.js - 退出模块,但不退出整个 NodeJS 进程

javascript - 在 Node 应用程序中定义路径树

seo - 使用 handlebars.js 时是否将 google 索引脚本标记作为内容

javascript - 客户端、服务器端、django 后端的混合模板

javascript - 数据表的省略号渲染

javascript - 用 Angular 显示json结果

python - 使用数据表和 flask 进行服务器端处理

node.js - Gulp/Node - SASS 编译错误

ember.js - 通过变量名获取属性