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

荒凉一梦 提交于 2019-12-12 01:09:35

问题


I can successfully load one JSON file as a data source for my Jade templates using Grunt, similar to this solution.

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. How to do it better in context of Grunt tasks?


回答1:


You can load as many json files as you like with this method:

    // 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. 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.




回答2:


You need to combine the Objects before you serve them to Jade. For this I would recommend to use 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!



来源:https://stackoverflow.com/questions/21021203/how-to-load-multiple-json-files-into-jade-templates-using-grunt

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