morlay
5/13/2014 - 11:16 AM

twig through gulp

twig through gulp

var Twig = require('twig');
var es = require('event-stream');

var gutil = require('gulp-util');

var PluginError = gutil.PluginError;
var ext = gutil.replaceExtension;

module.exports = function (options) {

  var opts = options || {};

  function compileTwig(file, callback) {

    var data = opts.data || {};

    if (file.isStream()) {
      this.emit('error', new gutil.PluginError('gulp-twig', 'Streaming not supported'));
      callback();
    }


    Twig.twig({
      path: file.path,
      base: file.base,
      load: function (template) {

        file.contents = new Buffer(template.render(data), 'utf-8');
        file.path = ext(file.path, '.html');

        console.log('file', file.path.substr(file.base.length), 'created');

        callback(null, file);

      }
    });
  }

  return es.map(compileTwig);

};