panthro
panthro

Reputation: 24061

Loop a grunt task?

I need to loop through my copy task and output in a different folder each time. How can I loop through it and provide a var to it each time? I have a variety of languages to output and each needs to go in its own folder.

copy:{
        files:{
            expand: true,
            cwd: '../',
            src: [
                'static/**',
            ],
            dest: '../../public/[language-folder-var]'
        }
    }

Upvotes: 2

Views: 1064

Answers (3)

theaccordance
theaccordance

Reputation: 889

In your config object, you can use template tags to inject data into strings:

copy:{
        files:{
            expand: true,
            cwd: '../',
            src: [
                'static/**',
            ],
            dest: "../../public/<%= grunt.option('lang') %>/"
        }
    }

Then you'll need a function that will iterate though the different languages, set the grunt.option variable, and run the task for each:

function compileLangFiles() {
    var langs = ['en', 'fr', 'jp'], lang;

    for (lang in langs) {
        grunt.option('lang', lang);
        grunt.task.run('copy');
    }
}

grunt.registerTask('copyLang', copyLangFiles);

Upvotes: 1

Andy
Andy

Reputation: 63524

Panthro, I imagine something like this.

Assuming a config.json like:

{ langs: ['en', 'fr', 'de'] }

Load it (auto-parsed)

grunt.langconfig = grunt.file.readJSON('config.json');
grunt.langs = grunt.langconfig.langs;

And in your iterate task join langs

argName: grunt.langs.join(',')

Upvotes: 0

Michael Oakley
Michael Oakley

Reputation: 383

If your copy task contains a lot of filetype specific handling, one route you can take is to make separate tasks for different file types.
e.g.
grunt.registerTask( 'build', ['copyjs','copycss'] );

If you have many filetypes, this wouldn't be advisable. In that case, you should dynamically create the targets (tasks). I would put the paths in an array and forEach loop over it, creating the tasks object within the loop.

Upvotes: 0

Related Questions