Ejemplo n.º 1
0
HandlebarsTemplate.prototype.execute = function(inputFile) {
    var self = this;
    var deferred = Q.defer();
    // Step 1: 读取输入文件的内容
    var content = inputFile.content;
    var source = inputFile.src;

    // Step 2: 先分析得到文件的id
    var id = StringUtils.lstrip(StringUtils.lstrip(self.toUnixPath(source),
        {source: self.options.rootPath}), {source: "/"}
    );
    if (_.isFunction(self.options.idRule)) {
        id = self.options.idRule.call(self, id);
    }

    // Step 3: 进行预编译
    var complied = Handlebars.precompile(content, {
        knownHelpers: self.options.handlebars.knownHelpers
    });

    // Step 4: 得到AMD格式的代码
    var code = amdTemplate({
        id: id,
        handlebars: self.options.handlebars,
        content: complied
    });
    code = self.beautify(code, "js");
    process.nextTick(function() {
        deferred.resolve(code);
    });
    return deferred.promise;
};
Ejemplo n.º 2
0
    }, function () {
        var precompile = Handlebars.precompile(buffer);
        precompile = 'module.exports = Handlebars.template(' + precompile + ');';

        if (options.module) {
            var hbsModule = options.module;
            if (hbsModule[0] === '.') {
                // use relative path to require Handlebars module
                // file: src/a/b/c/d.handlebars
                // module: src/d/e/Handlebars.js
                // --> hbsModule: ../../../../lib/Handlebars.js
                var from = path.dirname(file);
                hbsModule = './' + path.relative(from, path.resolve(options.root || '.', options.module));
            }

            if (hbsModule.indexOf('cjs') !== -1) {
                precompile = 'var Handlebars = require("' + hbsModule + '").default;' + precompile;
            } else {
                precompile = 'var Handlebars = require("' + hbsModule + '");' + precompile;
            }
        }

        this.queue(precompile);
        this.queue(null);
    });
Ejemplo n.º 3
0
HandlebarsCompiler.prototype.compile = function(data, path, callback) {
  if (this.optimize) {
    data = data.replace(/^[\x20\t]+/mg, '').replace(/[\x20\t]+$/mg, '');
    data = data.replace(/^[\r\n]+/, '').replace(/[\r\n]*$/, '\n');
  }

  var error, key, ns, result, source, header;
  try {
    source = "Handlebars.template(" + (handlebars.precompile(data)) + ")";

    if (typeof this.namespace === 'function') {
      ns = this.namespace(path);
    } else {
      ns = this.namespace;
    }

    if (ns) {
      key = ns + '.' + path.replace(/\\/g,'/').replace(this.pathReplace, '').replace(/\..+?$/, '').replace(/\//g,'.');
      result = "Handlebars.initNS( '" + key + "' ); " + key + " = " + source;
    } else {
      result = umd(source);
    }
  } catch (_error) {
    error = _error;
  }
  if (error) return callback(error);
  return callback(null, result);
};
Ejemplo n.º 4
0
  var compileHandlebars = function(contents, path) {
    // Perform pre-compilation
    // This will throw if errors are encountered
    var compiled = Handlebars.precompile(contents.toString(), options.compilerOptions);

    if (options.wrapped) {
      compiled = 'Handlebars.template('+compiled+')';
    }

    // Handle different output times
    if (options.outputType === 'amd') {
      compiled = "define(['handlebars'], function(Handlebars) {return "+compiled+";});";
    }
    else if (options.outputType === 'commonjs') {
      compiled = "module.exports = function(Handlebars) {return "+compiled+";};";
    }
    else if (options.outputType === 'node') {
      compiled = "module.exports = "+compiled+";";

      if (options.wrapped) {
        // Only require Handlebars if wrapped
        compiled = "var Handlebars = global.Handlebars || require('handlebars');"+compiled;
      }
    }

    return compiled;
  };
Ejemplo n.º 5
0
module.exports = function(content) {
    var js = Handlebars.precompile(content);
    var compiled = "var Handlebars = require('handlebars/runtime')['default'];\n";
    compiled += "module.exports = Handlebars.template(" + js.toString() + ");\n";

    return compiled;
}
Ejemplo n.º 6
0
			fetchText(path, function (text) {
				//Do Handlebars transform.
				text = Handlebars.precompile(text);
				text = "define(['handlebars'], function (Handlebars) { return Handlebars.template(" + text + "); });";

				//Hold on to the transformed text if a build.
				if (config.isBuild) {
					buildMap[name] = text;
				}

                /*@cc_on
                    /*@if (@_jscript)
                        //IE with conditional comments on cannot handle the sourceURL trick, so skip it if enabled.
                    @else @*/
                        if(!config.isBuild){
                            text += "\r\n//@ sourceURL=" + path;
                        }
                    /*@end
                @*/

				load.fromText(name, text);

				//Give result to load. Need to wait until the module
				//is fully parse, which will happen after this
				//execution.
				parentRequire([name], function (value) {
					load(value);
				});
			});
Ejemplo n.º 7
0
 var end = function() {
   var precomp = Handlebars.precompile(data);
   var template = 'var Handlebars = require("hbsify").runtime;\n';
   template += 'module.exports = Handlebars.template(' + precomp.toString() + ');\n';
   this.queue(template);
   this.queue(null); 
 };
Ejemplo n.º 8
0
 io.read(resId + ".hbs", function (text) {
     var code = util.format(
         "Handlebars.template(%s);",
         handlebars.precompile(text)
     );
     io.write(_define(absId, ['handlebars'], '', '', code));
 }, io.error);
    build.map('templates', function(file, conf){
      var ext = path.extname(file.filename);
      if (extname != ext) return file;

      var absolutepath = conf.path(file.filename);
      var filename = path.basename(absolutepath, extname);

      var src = read(absolutepath, 'utf-8');
      if(minify) src = src.replace(/[\n\t\r]+/g, '');
      
      var compiled = Handlebars.precompile(src);
      var output = 'Handlebars.template(' + compiled + ')';

      if (partialRegex.test(filename)) {
        var modulePath = file.filename.replace(filename + extname, '');
        filename = filename.replace(partialRegex, '');
        partials.push('Handlebars.registerPartial("' + conf.name + '/' + modulePath + filename + '", ' + output + ');');
      }

      var script = {};
      script.filename = file.filename.replace(extname, '.js');
      script.contents = 'module.exports = ' + output;
      conf.scripts = conf.scripts || [];
      conf.scripts.push(script);

      return file;
    });
Ejemplo n.º 10
0
  return through(function(file) {
    if (file.isNull()) {
      return this.queue(file);
    }

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

    var contents = file.contents.toString();
    var compiled = null;
    try {
      compiled = Handlebars.precompile(contents, compilerOptions).toString();
    }
    catch (err) {
      return this.emit('error', err);
    }

    file.contents = new Buffer(compiled);
    file.path = gutil.replaceExtension(file.path, '.js');

    // Options that take effect when used with gulp-define-module
    file.defineModuleOptions = {
      require: {
        Handlebars: 'handlebars'
      },
      context: {
        handlebars: 'Handlebars.template(<%= contents %>)'
      },
      wrapper: '<%= handlebars %>'
    };

    this.queue(file);
  });
Ejemplo n.º 11
0
			fs.readFile(file, function(err, content) {
				if(err) return cb(err);

				var name = templateName(file);
				var segments = name.split('.');

				for(var i = 0; i < segments.length - 1; i++) {
					var e = segments.slice(0, i + 1).join('.');

					if(namespaces.indexOf(e) === -1) {
						namespaces.push(e);

						var namespaceContent = util.format("module.exports.%s = {};", e);
						output.push(namespaceContent);
					}
				}

				var content = util.format(
					"module.exports.%s = Handlebars.template(%s);\n",
					name,
					handlebars.precompile(content.toString(), {})
				);

				output.push(content);
				cb();
			});
Ejemplo n.º 12
0
      .forEach(function(filepath, index, list) {
        var src = processContent(grunt.file.read(filepath), filepath);

        var Handlebars = require('handlebars');
        try {
          // parse the handlebars template into it's AST
          ast = processAST(Handlebars.parse(src));
          compiled = Handlebars.precompile(ast, compilerOptions);

          // if configured to, wrap template in Handlebars.template call
          if (options.wrapped === true) {
            compiled = 'Handlebars.template(' + compiled + ')';
          }
        } catch (e) {
          grunt.log.error(e);
          grunt.fail.warn('Handlebars failed to compile ' + filepath + '.');
        }

        // register partial or add template to namespace
        if (partialsPathRegex.test(filepath) && isPartialRegex.test(_.last(filepath.split('/')))) {
          filename = processPartialName(filepath);
          if (options.partialsUseNamespace === true) {
            nsInfo = getNamespaceInfo(filepath);
            if (nsInfo.declaration) {
              declarations.push(nsInfo.declaration);
            }
            partials.push('Handlebars.registerPartial(' + JSON.stringify(filename) + ', ' + nsInfo.namespace +
              '[' + JSON.stringify(filename) + '] = ' + compiled + ');');
          } else {
            partials.push('Handlebars.registerPartial(' + JSON.stringify(filename) + ', ' + compiled + ');');
          }
        } else {
          filename = processName(filepath);

          if ((options.amd || options.commonjs) && !useNamespace) {
            if (list.length > 1) {
              compiled = '\'' + filename + '\': ' + compiled;

              if (index < list.length-1) {
                // not the last item in object, so add coma
                compiled = compiled + ',';
              }
            } else {
              compiled = 'return ' + compiled;
            }
          }
          
          if (useNamespace) {
            nsInfo = getNamespaceInfo(filepath);
            if (nsInfo.declaration) {
              declarations.push(nsInfo.declaration);
            }
            templates.push(nsInfo.namespace + '[' + JSON.stringify(filename) + '] = ' + compiled + ';');
          } else if (options.commonjs === true) {
            templates.push(compiled + ';');
          } else {
            templates.push(compiled);
          }
        }
      });
Ejemplo n.º 13
0
 files.forEach(function(file) {
   var name = path.basename(file,'.hbs');
   var filepath = metalsmith.path(options.directory, file);
   var fileContents = fs.readFileSync(filepath, {encoding: 'utf8'});
   var precompiled = handlebars.precompile(fileContents, {srcName: file, knownHelpers: options.knownHelpers});
   var template = 'Handlebars.templates.' + name + ' = Handlebars.template(' + precompiled.code + ');\n';
   combo += template;
 });
Ejemplo n.º 14
0
module.exports = function(content, options, fn) {
	try {
		content = 'module.exports = Handlebars.template(' + handlebars.precompile(content, extend({}, SETTINGS, options)) + ');';
		return fn(null, content);
	} catch (err) {
		return fn(err, content);
	}
};
Ejemplo n.º 15
0
 function() {
   var js = Handlebars.precompile(buffer);
   // Compile only with the runtime dependency.
   var compiled = "var Handlebars = require('handlebars-runtime');\n";
   compiled += "module.exports = Handlebars.template(" + js.toString() + ");\n";
   this.queue(compiled);
   this.queue(null);
 });
Ejemplo n.º 16
0
 return function(next) {
   var data = this.data;
   var name = fixName( this.path );
   
   this.data = "/" + "* Compiled from  " + this.path + " *" + "/\n" +
               pre + name + mid + handlebars.precompile(data) + post + "\n";
   this.save['plain'] = this.data;
   next();
 };
Ejemplo n.º 17
0
  through.obj(function(file, enc, done) {
    const res = Handlebars.precompile(file.contents.toString(), {
      strict: false,
      data: false
    });

    file.contents = new Buffer(res);
    done(null, file);
  });
Ejemplo n.º 18
0
 fs.readFile(file, 'utf8', function (err, file) {
   if (err) return next(err);
   content += '/* ' + key + ' */\n';
   content += '(function() {\n';
   content += "templates['" + key + "'] = Handlebars.template(\n\n";
   content += Handlebars.precompile(file);
   content += '\n\n);\n';
   content += '})();\n\n';
   templateDone();
 });
Ejemplo n.º 19
0
HandlebarsCompiler.prototype.compile = function(data, path, callback) {
  var error, key, ns, result, source;
  try {
    source = "Handlebars.template(" + (handlebars.precompile(data)) + ")";
    result = this.namespace ? (ns = this.namespace, key = path.replace(/^.*templates\//, '').replace(/\..+?$/, ''), "if (typeof " + ns + " === 'undefined'){ " + ns + " = {} }; " + ns + "['" + key + "'] = " + source) : umd(source);
  } catch (_error) {
    error = _error;
  }
  if (error) return callback(error);
  return callback(null, result);
};
Ejemplo n.º 20
0
 compile: function (raw, name, dir) {
     return {
         filename: path.join(dir, name + ".js"), 
         content: [
             'import compile from "lib/templates";',
             'export var raw = `' + handlebars.precompile(raw) + '`;',
             'export var template = compile(raw);',
             'export default template;'
         ].join("\n")
     };
 }
Ejemplo n.º 21
0
    context.fileUtil.readFileArtifact(name, 'template', function(err, cache) {
      if (err) {
        callback(new Error('Failed to load template "' + name + '"\n\t' + err));
        return;
      }

      var artifact = cache.artifact || {},
          data = artifact.data || cache.data.toString(),
          attr = context.config.attributes,
          templates = attr.templates || attr.views,
          appModule = context.config.scopedAppModuleName(context.module),
          templateCache = (context.config.attributes.templates && context.config.attributes.templates.cache) ||
            context.config.attributes.templateCache ||
            ((appModule ? appModule + '.' : '') + 'templates'),
          template = context.configCache.templateTemplate;

      // We have the template data, now convert it into the proper format
      name = templateUtil.escapeJsString(name);
      if (!cache.artifact) {
        if (templates.precompile) {
          var options = context.configCache.precompileTemplates;
          if (!options) {
            context.configCache.precompileTemplates = options = _.clone(templates.precompile);
            if (options.knownHelpers) {
              options.knownHelpers = options.knownHelpers.reduce(
                  function(value, helper) {
                    value[helper] = true;
                    return value;
                  }, {});
            }
          }
          try {
            data = handlebars.precompile(data, options);
            template = context.configCache.precompiledTemplate;
          } catch (err) {
            return callback(err);
          }
        } else {
          data = templateUtil.escapeJsString(data);
        }
        context.fileUtil.setFileArtifact(name, 'template', {data: data, template: template});
      } else {
        template = artifact.template;
      }

      callback(
        undefined,
        template({
          name: name,
          templateCache: templateCache,
          data: data
        })
      );
    });
Ejemplo n.º 22
0
 factoryParser: function(data, options) {
   patchHandlebars(handlebars);
   var code = handlebars.precompile(data, options.handlebars);
   var template = [
     'function(require, exports, module) {',
       'var Handlebars = require("%s");',
       'var template = Handlebars.template;',
       'module.exports = template(%s);',
     '}'
   ].join('\n');
   return format(template, options.handlebars.id, code);
 }
      file.src.forEach(function (src) {
        var template = grunt.file.read(src),
          fileExtname = path.extname(src),
          outputFilename = path.basename(src, fileExtname),
          outputFilepath = file.dest + outputFilename + '.js',
          output = [];

        output.push('define([\'handlebars\'], function(Handlebars) {\n');
        output.push('return Handlebars.template(' + Handlebars.precompile(template) + ');\n');
        output.push('});');

        grunt.file.write(outputFilepath, output.join(''));
      });
Ejemplo n.º 24
0
  function processTemplate(template, root) {
    var path = template,
        stat = fs.statSync(path);

    // make the filename regex user-overridable
    var fileRegex = /\.handlebars$/;
    if(opts.fileRegex) fileRegex = opts.fileRegex;
    
    if (stat.isDirectory()) {
      fs.readdirSync(template).map(function(file) {
        var path = template + '/' + file;

        if (fileRegex.test(path) || fs.statSync(path).isDirectory()) {
          processTemplate(path, root || template);
        }
      });
    } else {
      var data = fs.readFileSync(path, 'utf8');

      var options = {
        knownHelpers: known,
        knownHelpersOnly: opts.o
      };

      // Clean the template name
      if (!root) {
        template = basename(template);
      } else if (template.indexOf(root) === 0) {
        template = template.substring(root.length+1);
      }
      template = template.replace(fileRegex, '');

      if (opts.simple) {
        output.push(handlebars.precompile(data, options) + '\n');
      } else {
        output.push('templates[\'' + template + '\'] = template(' + handlebars.precompile(data, options) + ');\n');
      }
    }
  }
                        return files.map(function(filepath) {
                            var filecontent = grunt.file.read(filepath),
                                precompiled = Handlebars.precompile(Handlebars.parse(filecontent)),
                                template;

                            template = this.precompileTemplate({
                                filepath: filepath,
                                template: precompiled,
                                opts: options.opts
                            });

                            return template;
                        }, this);
Ejemplo n.º 26
0
  exports.handlebarsParser = function(fileObj, options) {
    var dest = fileObj.dest + '.js';
    grunt.log.writeln('Transport ' + fileObj.src + ' -> ' + dest);

    var handlebars = require('handlebars');

    // id for template
    var id = options.idleading + fileObj.name.replace(/\.js$/, '');

    // handlebars alias
    var alias = iduri.parseAlias(options, 'handlebars');

    var template = [
      'define("%s", ["%s"], function(require, exports, module) {',
      'var Handlebars = require("%s");',
      'var template = Handlebars.template;',
      'module.exports = template(',
      '%s',
      ');',
      '})'
    ].join('\n');

    var data = fileObj.srcData || grunt.file.read(fileObj.src);

    patchHandlebars(handlebars);
    var code = handlebars.precompile(data, options.handlebars);

    var ret = format(template, id, alias, alias, code);
    var astCache = ast.getAst(ret);

    data = astCache.print_to_string(options.uglify);
    grunt.file.write(dest, data);

    // create debug file
    if (!options.debug) {
      return;
    }
    dest = dest.replace(/\.handlebars\.js$/, '-debug.handlebars.js');
    grunt.log.writeln('Creating debug file: ' + dest);

    astCache = ast.modify(astCache, function(v) {
      var ext = path.extname(v);
      if (ext && options.parsers[ext]) {
        return v.replace(new RegExp('\\' + ext + '$'), '-debug' + ext);
      } else {
        return v + '-debug';
      }
    });
    data = astCache.print_to_string(options.uglify);
    grunt.file.write(dest, data);
  };
Ejemplo n.º 27
0
var precompileTemplate = function(path)
{
  if (precompiled.has(path))
  {
    return precompiled.get(path);
  }
  var file = fs.readFileSync(__dirname + "/" + path + ".html", 'utf-8');
  logger.debug("Precompiling Template '" + __dirname + "/" + path + "'");

  var fileCompiled = handlebars.precompile(file);
  compiled.set(path, fileCompiled);

  return fileCompiled;
};
Ejemplo n.º 28
0
    _processFile: function(options, path, template, root, self, output, stat) {
        // Clean the template name
        if (template.indexOf(root) === 0) {
            template = template.substring(root.length+1);
        }
        var key = template.replace(options.exts_re, '');

        var cache = options.cache === undefined ? self.defaults.cache : options.cache;
        if ( cache === false || options.timestamps[key] === undefined || options.timestamps[key] && options.timestamps[key].ts.getTime() != stat.mtime.getTime() ) {
            var data = fs.readFileSync(path, options.encoding || self.defaults.encoding );
            options.timestamps[key] = { ts: stat.mtime, _template: handlebars.precompile(data, options) };
        }
        output.push('templates[\'' + key + '\'] = template(' + options.timestamps[key]._template + ');\n');
    }
Ejemplo n.º 29
0
    /**
     * Generates a requirejs module containing the precompiled version of the template. (ie the template function)
     * @param templatePath - required - full path to the .html template file
     * @param templateName - required - name of the template and partial as it will be registered with handlebars. eg Handlebars.template[templateName]; Handlebars.registerPartial(templateName, ...);
     * @param outputPathAndFileName - required - full path to where the compiled template should be placed.
     */
    function precompileHandlebarsTemplate(templatePath, templateName, outputPathAndFileName){
        log('precompileHandlebarsTemplate called.');
        var FILE_ENCODING = 'utf-8';
        //first grab the html from the template file
        var templateSrc = grunt.file.read(templatePath);//fs.readFileSync(templatePath, FILE_ENCODING);
        //generate the js function for the template
        var templateFunction = handlebars.precompile(templateSrc);
        //wrap the generated template function as a require js module
        var wrappedTemplateFunction = wrapCompiledHandlebarsTemplateAsModule(templateName, templateFunction);

        //write out the require module to disk.
        //fs.writeFileSync(outputPathAndFileName, wrappedTemplateFunction, FILE_ENCODING);
        grunt.file.write(outputPathAndFileName, wrappedTemplateFunction);
        console.log('done compiling template ' + templateName);
    }
Ejemplo n.º 30
0
const compileEmail = filename => {
  fs.readdirSync('src/emails').forEach(file => {
    if (file.endsWith('.hbs')) {
      const partial = fs
        .readFileSync(`src/emails/${file}`, 'utf8')
        .replace(/{{/g, '\\{{')
        .replace(/\\{{(#block|\/block)/g, '{{$1');
      handlebars.registerPartial(file.substr(0, file.length - 4), partial);
    }
  });
  const template = fs
    .readFileSync(filename, 'utf8')
    .replace(/{{/g, '\\{{')
    .replace(/\\{{(#extend|\/extend|#content|\/content)/g, '{{$1');
  return handlebars.precompile(juice(handlebars.compile(template)({})));
};