简体   繁体   English

如何使用Grunt将多个JSON文件加载到Jade模板中?

[英]How to load multiple JSON files into Jade templates using Grunt?

I can successfully load one JSON file as a data source for my Jade templates using Grunt, similar to this solution . 类似于此解决方案 ,我可以使用Grunt成功地将一个JSON文件作为Jade模板的数据源加载。

Now I need to load a set of JSON files from different folders inside my project so that all the data from them is accessible from Jade templates. 现在,我需要从项目内的不同文件夹中加载一组JSON文件,以便可以从Jade模板访问其中的所有数据。 How to do it better in context of Grunt tasks? 如何在Grunt任务中做得更好?

You can load as many json files as you like with this method: 您可以使用此方法加载任意数量的json文件:

    // Jade => HTML
gruntConfig.jade = {
    compile: {
        options: {
            data: {
                object: grunt.file.readJSON('JSON_FILE.json'),
                object1: grunt.file.readJSON('JSON_FILE_1.json'),
                object2: grunt.file.readJSON('JSON_FILE_2.json'),

            }
        },
    }
};

And then in the Jade template you simply need to reference the object. 然后,在Jade模板中,您只需要引用该对象。 IE: IE浏览器:

    script(src= object.baseURL + "js/vendor/jquery.js")
    script(src= object.baseURL + "js/vendor/elementQuery.js")
    script(data-main="js/main", src= object.baseURL + "js/vendor/require.js")

I know this is being answered a bit late but for anyone who comes across this from a google search as I have, this is the answer to loading multiple JSON files into a Jade template using Grunt.js. 我知道这个答案来得有点晚,但是对于任何像我一样从Google搜索中遇到的人,这就是使用Grunt.js将多个JSON文件加载到Jade模板中的答案。

You need to combine the Objects before you serve them to Jade. 您需要先组合对象,然后再将它们提供给Jade。 For this I would recommend to use Underscore.js. 为此,我建议使用Underscore.js。

Personally I would write a method to fetch the data from the files, like this: 我个人将编写一种从文件中获取数据的方法,如下所示:

module.exports = function(grunt) {

    function combineJSONFiles() {
        var object = {};

        for(var i=0; i<arguments.length; ++i) {
            _(object).extend(grunt.file.readJSON(arguments[i]));
        }

        return object;
    }

    grunt.loadNpmTasks('grunt-contrib-jade');

    grunt.initConfig(
    {
        jade: {
            html: {
                src: './*.jade',
                dest: './index2.html',
                options: {
                    client: false,
                    pretty: true,
                    data: combineJSONFiles(
                        "1.json",
                        "2.json",
                        "3.json"
                    )
                }
            }
        }
    });

    grunt.registerTask('default', 'jade');
};

Hope that helps! 希望有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM