Providing data models to use in Gulp Nunjucks templates

半世苍凉 提交于 2020-01-23 03:42:06

问题


I'm looking to use Gulp to render my Nunjucks templates with either gulp-nunjucks or gulp-nunjucks-render. Is there a way I can pass one or a series of .json files to the templating package to use the JSON data in my nunjucks templates?

Ideally I'd have a models/ directory with each page having corresponding page.json file with contents to be used in that template.

I'd like to know if it's possible with either of the above plugins and if so how it can be implemented. Any examples for a single or series of .json files would be very useful.


回答1:


Look into using gulp-data https://www.npmjs.org/package/gulp-data it produces JSON from a any source, be it a JSON file, or database, that sends it down the stream via a new attribute on the file object (file.data). Your nunjucks plugin will need to be modified to consume that data property.




回答2:


This worked for me, but in my case it didn't do quite everything I needed. With my gulpfile like the following:

//Compile Nunjucks Templates
gulp.task('nunjucks', function() {
    nunjucksRender.nunjucks.configure(['templates/'])
    return gulp.src('src/pages/*.html')
        .pipe(nunjucksRender(nunjucksOptions))
        .pipe(gulp.dest(output.html))
        .pipe(reload({stream:true}));
});

Using gulp-data here to inject my JSON only provides data to the pages, and not to partials and macros I'm including. In my case, I'm using a central JSON settings file to emulate, for example, what my front end will look like when a user logs in:

{
    "loggedin":false
}

and

{% if data.loggedin %}
<a href="#" class="nav__item nav__item--login">
    <div class="nav__item--login_img">
        <img src="http://pipsum.com/200x200.jpg" alt="" />
    </div>
    <p class="nav__item--login_user">JohnDoe345</p>
</a>
{% else %}
<a href="#login" data-lity class="nav__item nav__item--login">
    <div class="nav__item--login_cta">Sign In</div>
</a>
{% endif %}

To make the file accessible to all templates/pages/partials/macros/etc. I'm using gulp-nunjucks-render's manageEnv setting as follows:

nunjucksOptions = {
    path: ['src/pages/', 'src/templates/'],
    watch:true,
    manageEnv:function(env){
        var data = JSON.parse(fs.readFileSync('states.json'));
        env.addGlobal('data',data);
    }
}

Thanks to Alex Ward for the tip on using fs for keeping my JSON from being cached.



来源:https://stackoverflow.com/questions/26315911/providing-data-models-to-use-in-gulp-nunjucks-templates

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!