How to use the handlebars.precompile function in handlebars

To help you get started, we’ve selected a few handlebars examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github chrisabrams / The-Tramp / test / modules / handlebars.js View on Github external
.forEach(function(filepath) {
        var src = grunt.file.read(filepath);
        var compiled, filename;
        try {
          compiled = require('handlebars').precompile(src);
          // if configured to, wrap template in Handlebars.template call
          if (options.wrapped) {
            compiled = 'Handlebars.template('+compiled+')\n';
          }
        } catch (e) {
          grunt.log.error(e);
          grunt.fail.warn('Handlebars failed to compile '+filepath+'.');
        }

        // register partial or add template to namespace
        if (isPartial.test(_.last(filepath.split('/')))) {
          filename = processPartialName(filepath);
          partials.push('Handlebars.registerPartial('+JSON.stringify(filename)+', '+compiled+');');
        } else {
          filename = processName(filepath);
          templates.push("Handlebars = require('handlebars')")
github pmlopes / vertx-starter / gulpfile.js View on Github external
return callback();
    }

    const contents = file.contents.toString();
    let compiled = null;

    // binary files
    if (['favicon.ico'].indexOf(file.path.substr(file.path.lastIndexOf('/') + 1)) !== -1) {
      // binary file are stored as is
      compiled =
        "{\"compiler\":[7,\">= 4.0.0\"],\"main\":function(container,depth0,helpers,partials,data) {\n" +
        "    return " + JSON.stringify(contents) + ";\n" +
        "},\"useData\":false}\n";
    } else {
      try {
        compiled = handlebars.precompile(
          handlebars.parse(contents),
          compilerOptions
        ).toString();
      } catch (err) {
        console.log(err);
        this.emit('error', new PluginError("Handlebars plugin", err, {
          fileName: file.path
        }));
        return callback();
      }
    }

    file.contents = Buffer.from(compiled);
    file.templatePath = file.relative;
    file.path = gutil.replaceExtension(file.path, '.js');
github mattacular / grunt-handlebars-compiler / tasks / handlebars.js View on Github external
filename = processFilename(filepath);

				if (options.compress) {
					src = src.split("\n");

					for (var i = 0; i < src.length; i++) {
						if (src[i].charAt(0) !== '<') {
							src[i] = '{{!~}}' + src[i];
						}
					}

					src = src.join("\n");
				}

				try {
					compiled = require('handlebars').precompile(src, compilerOptions);
				} catch (e) {
					grunt.log.error(e);
					grunt.fail.warn('Handlebars failed to compile '+filepath+'.');
				}

				// source is compiled at this point, let us reconstruct and decide wrappings
				if (options.partials) {
					wrapOpen = 'Handlebars.partials[\'' + filename + '\'] = template(';
				} else {
					wrapOpen = 'templates[\'' + filename + '\'] = template(';
				}

				// This optionally returns the template as well as adding it to the Handlebars.templates object for immediate use in AMD modules
				if (options.returnAMD)
				{
					wrapClose = ');return templates[\''+filename+'\'];\n';
github abecms / abecms / src / cli / cms / Page.js View on Github external
}
          }
        }
      }
     
      this._addSource(json)

      // We remove the {{abe type=data ...}} from the text 
      this.template = cmsData.source.removeDataList(this.template)

      // It's time to replace the [index] by {{@index}} (concerning each blocks)
      this.template = this.template.replace(/\[index\]\./g, '{{@index}}-')

      if(config.files.templates.precompile){
        // Let's persist the precompiled template for future use (kind of cache)
        fse.writeFileSync(this.HbsTemplatePath, Handlebars.precompile(this.template), 'utf8')
        Manager.instance.addHbsTemplate(templateId)
      }

      // I compile the text
      var compiledTemplate = Handlebars.compile((!this._onlyHTML) ? cmsTemplates.insertDebugtoolUtilities(this.template) : this.template)

      // I create the html page ! yeah !!!
      this.html = compiledTemplate(json, {data: {intl: config.intlData}})
    }

    if(this._onlyHTML) {
      this.html = Hooks.instance.trigger('afterPageSaveCompile', this.html, json)
    }else {
      this.html = Hooks.instance.trigger('afterPageEditorCompile', this.html, json)
    }
  }
github Zettlr / Zettlr / scripts / handlebars.js View on Github external
try {
    fs.lstatSync(output)
  } catch (e) {
    log.info(`Creating directory ${output} ...`)
    fs.mkdirSync(output)
  }

  let templates = fs.readdirSync(input)

  for (let tpl of templates) {
    if (path.extname(tpl) !== '.handlebars') continue // Only compile handlebars
    try {
      // Read the file
      let inTpl = fs.readFileSync(path.join(input, tpl), 'utf8')
      // Compile
      let compiled = handlebars.precompile(inTpl)
      // The resultant file is basically a JavaScript function so to prevent strange
      // effects simply append a ".js".
      // ATTENTION! As the NodeJS function does NOT generate standalone files, we
      // have to wrap this with module.exports to ensure it is possible to require
      // the template at runtime!
      fs.writeFileSync(path.join(output, `${tpl}.js`), `module.exports = ${compiled}`, 'utf8')
      log.success(`Compiled ${tpl}!`)
    } catch (e) {
      log.error(`Error compiling ${tpl}: ${e.message}`)
    }
  }
}
github taylorhughes / skit / lib / loader / scriptresource.js View on Github external
if (dependencyPath != HandlebarsResource.HANDLEBARS_MODULE) {
      // All other dependencies are partials.
      partials.push(alias);
    }
  }, this);

  // Don't look at me that way. I know. I KNOW!
  var partialDeclarations = partials.map(function(alias) {
    return JSON.stringify(alias) + ': ' + alias;
  });
  var partialMapString = '{' + partialDeclarations.join(',') + '}';

  var template;
  try {
    // TODO(Taylor): Allow other options to be passed in somehow.
    template = Handlebars.precompile(source, {
      preventIndent: true
    });

  } catch (e) {
    e.fileName = this.filePath;
    var lineNumberMatch = (e+'').match(/Parse error on line (\d+)/);
    if (lineNumberMatch) {
      e.lineNumber = +(lineNumberMatch[1]);
    }
    throw e;
  }

  var wrapped = [
    '(function(' + args.join(',') + ') {',
    '  var template = Handlebars.VM.template(' + template + ', Handlebars);',
    '  var partials = ' + partialMapString + ';' +
github spmjs / grunt-cmd-transport / tasks / lib / template.js View on Github external
var alias = options.handlebars.id;

    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');

    astCache = ast.modify(astCache, function(v) {
      var ext = path.extname(v);
      if (ext && options.parsers[ext]) {
github popeindustries / buddy / lib / processors / compilers / handlebars.js View on Github external
compile: function(data, filepath, fn) {
		try {
			// Compile without function wrapper
			var compiled = handlebars.precompile(data, {simple:true, amd:true});
			fn(null, 'module.exports = Handlebars.template(' + compiled + ');');
		} catch (err) {
			fn(err, '');
		}
	}
};
github Cu3PO42 / KeySAVe / src / components / formatters / handlebars / FormattingOptionsHandlebars.js View on Github external
format => {
      try {
        handlebars.precompile(format);
        return null;
      } catch (e) {
        return <div>Your template string is invalid.</div>;
      }
    }
  );
github oracle / netsuite-suitecloud-node-cli / src / sdf-cli-local / src / compilers / TemplatesCompiler.js View on Github external
template.sourceContent().then(content => {
				template.setPrecompiled(handlebars.precompile(content));

				template.applications.forEach(app => {
					const basename = template.getBasename();
					this.entrypoints[app] = this.entrypoints[app] || {};
					this.entrypoints[app][basename] = basename;
				});

				//write final template file:
				template.logOverrideMessage();
				return FileSystem.writeFile(
					path.join(this.processedTemplatesPath, template.dst),
					this._wrapTemplate(template)
				);
			});
	}