【问题标题】:How do I access the Data Object created by the gulp-gray-matter plugin (when compiling html files with nunjucks)如何访问由 gulp-gray-matter 插件创建的数据对象(使用 nunjucks 编译 html 文件时)
【发布时间】:2016-07-27 05:10:09
【问题描述】:

我正在使用nunjucks-render 作为前端 JavaScript 模板引擎。

我想从某些 .nunjuck 文件中读取正面物质数据,然后在将我的 .nunjuck(模板)文件编译成 .html 文件时使用该数据。

经过一番研究,我发现gulp-gray-matter 是更快更好的额叶物质提取插件之一。

我的问题是:我现在如何访问正面物质数据对象?

例如,我会将正面问题写在 .nunjucks 文件中:

---
title: Welcome to ACME Co.
---

<title>{{ data.title }}</title>

最终的 HTML 输出应该是:

<title>Welcome to ACME Co.</title>

我的 gulfile.js 设置如下:

var gulp = require('gulp'),
    nunjucks = require('gulp-nunjucks-render')
    gulpGrayMatter = require('gulp-gray-matter');

    gulp.task("nunjucks", function(){
        return gulp.src(src/templates/**/*.+(nunjucks|njk))
            .pipe(gulpGrayMatter()) //send files through gray-matter plugin to extract frontal-matter
            .pipe(nunjucks({
                path: src/templates
            })) 
            .pipe(gulp.dest(src));
    });

【问题讨论】:

    标签: javascript node.js gulp nunjucks yaml-front-matter


    【解决方案1】:

    默认情况下,gulp-gray-matter 将所有前沿数据存储在流中每个文件的 data 属性中。

    默认情况下gulp-nunjucks-render 使用流中每个文件的data 属性中存在的数据。

    因此,您实际上不必在 Gulpfile 中做任何花哨的事情。这将起作用:

    gulp.task('nunjucks', function(){
        return gulp.src('src/templates/**/*.nunjucks')
            .pipe(gulpGrayMatter())
            .pipe(nunjucks()) 
            .pipe(gulp.dest('dest'));
    });
    

    但是,您必须正确访问 .nunjuck 模板中的数据:

    ---
    title: Welcome to ACME Co.
    ---
    
    <title>{{ title }}</title>
    

    【讨论】:

    • 这样一个简单的答案...... 4 小时后,我可以继续我的生活。谢谢:)
    猜你喜欢
    • 2015-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-02
    • 1970-01-01
    相关资源
    最近更新 更多