mtpultz mtpultz - 1 month ago 18
Javascript Question

Can Grunt Lodash Templates Be Used In Gruntfile.js tasks?

Is there a way to use grunt lodash templating in gruntfile.js tasks so I can use functions like .toLowerCase(). The below snippet doesn't work, maybe it doesn't work this way since I can't find an example that fits this use case.

copy: {
plugins: {
files: [{
src: ['<%= root %>/<%= dirs.plugins %>/<%= pkg.name.toLowerCase() %>'],
dest: '<%= root %>/<%= dirs.www %>/wp-content/plugins/<%= pkg.name %>',
}]
}
}

Answer

Use the evaluate delimiter <% plus the String() constructor to use toLowerCase:

src: ['<% String(pkg.name).toLowerCase() %>']

Use npm install to use lodash:

npm install lodash --save-dev

Then add the require statement to your Gruntfile.js:

var _ = require('lodash');
var newArr = _.map(arr, fn);

By default, the template delimiters used by lodash are like those in embedded Ruby (ERB). Change the following template settings to use alternative delimiters.

_.templateSettings = 
  {
  evaluate    : /<%([\s\S]+?)%>/g,
  interpolate : /<%=([\s\S]+?)%>/g,
  escape      : /<%-([\s\S]+?)%>/g
  };

References