How to use handlebars

Comprehensive handlebars code examples:

How to use handlebars.Compiler:

254
255
256
257
258
259
260
261
262
263
264
265
      mustache.hash.pairs.push(["unescaped", new Handlebars.AST.StringNode("true")]);
    }
    mustache = new Handlebars.AST.MustacheNode([id].concat([mustache.id]), mustache.hash, !mustache.escaped);
  }


  return Handlebars.Compiler.prototype.mustache.call(this, mustache);
};


/**
  Used for precompilation of Ember Handlebars templates. This will not be used

How to use handlebars.JavaScriptCompiler:

9
10
11
12
13
14
15
16
17
var _ = require('lodash');
var handlebars = require('handlebars');
var helpers = null;

// Custom nameLookup
var nameLookup = handlebars.JavaScriptCompiler.prototype.nameLookup;
handlebars.JavaScriptCompiler.prototype.nameLookup = function (parent, name, type) {
  return name.indexOf("root") === 0 ? 'data' : nameLookup(parent, name, type);
};

How to use handlebars.logger:

775
776
777
778
779
780
781
782
783
784
})

//DEBUG: https://gist.github.com/karlwestin/3487951
//Put {{log 0 item}} anywhere in template to print out 'item'
handlebars.logger.log = function(level) {
  if(level >= handlebars.logger.level) {
    //console.log.apply(console, [].concat(["Handlebars: "], _.toArray(arguments)));
    console.log.apply(console, arguments)
  }
}

How to use handlebars.precompile:

133
134
135
136
137
138
139
140
141
142
143
    res.header('Content-Type', 'text/html');
    res.send(data);
}


function respondFull(req, res, next) {
    var template = Handlebars.precompile(req.params.source);
    template = template.toString();
    //console.log(template);
    eval("var template2 = " + template);
    console.log(template2);

How to use handlebars.template:

25
26
27
28
29
30
31
32
33
34
const code = fs.readFileSync(filename, "utf8");
const pc = hb.precompile(code, {preventIndent: true, srcName: filename});
const node = new SourceNode();
node.add([
    'const Handlebars = require("handlebars/runtime");\n',
    "module.exports = Handlebars.template(",
    SourceNode.fromStringWithSourceMap(pc.code, new SourceMapConsumer(pc.map)),
    ");\n",
]);
const out = node.toStringWithSourceMap();

How to use handlebars.Visitor:

58
59
60
61
62
63
64
65
66
67
68
}


function buildThemeRawHbsTemplateManipulatorPlugin(themeId) {
  return function (ast) {
    ["SubExpression", "MustacheStatement"].forEach((pass) => {
      let visitor = new Handlebars.Visitor();
      visitor.mutating = true;
      visitor[pass] = (node) => manipulateAstNodeForTheme(node, themeId);
      visitor.accept(ast);
    });

How to use handlebars.escapeExpression:

32
33
34
35
36
37
38
39
40
41
	trialEndAt = new Date(company.get('trialEndDate')).toISOString();
}
if (company && company.get('testGroups')) {
	// this has to be a string that looks like an array in javascript
	abTest = '[' + Object.keys(company.get('testGroups')).map(key => {
		const safe = Handlebars.escapeExpression(`${key}|${company.get('testGroups')[key]}`);
		return `"${safe}"`;
	}).join(',') + ']';
} else {
	abTest = '[]';

How to use handlebars.create:

40
41
42
43
44
45
46
47
48
49
    case 'v4':
        this.handlebars = HandlebarsV4.create();
        break;
    case 'v3':
    default:
        this.handlebars = HandlebarsV3.create();
        break;
}

this.logger = logger;

How to use handlebars.parse:

68
69
70
71
72
73
74
75
76
77
78
79
RawHandlebars.JavaScriptCompiler.prototype.compiler =
  RawHandlebars.JavaScriptCompiler;
RawHandlebars.JavaScriptCompiler.prototype.namespace = "RawHandlebars";


RawHandlebars.precompile = function (value, asObject) {
  let ast = Handlebars.parse(value);
  replaceGet(ast);


  let options = {
    knownHelpers: {

How to use handlebars.AST:

237
238
239
240
241
242
243
244
245
246
  @for Ember.Handlebars.Compiler
  @param mustache
*/
Ember.Handlebars.Compiler.prototype.mustache = function(mustache) {
  if (mustache.isHelper && mustache.id.string === 'control') {
    mustache.hash = mustache.hash || new Handlebars.AST.HashNode([]);
    mustache.hash.pairs.push(["controlID", new Handlebars.AST.StringNode(prefix + incr++)]);
  } else if (mustache.params.length || mustache.hash) {
    // no changes required
  } else {

How to use handlebars.Utils:

54
55
56
57
58
59
60
61
62
// Handlebars.registerHelper('formatdate', function(text) {
// 	return new Handlebars.SafeString(text.slice(0,7));
// });

Handlebars.registerHelper('breaklines', function(text) {
	text = Handlebars.Utils.escapeExpression(text);
	text = text.replace(/(\r\n|\n|\r)/gm, '<br>');
	return new Handlebars.SafeString(text);
});

How to use handlebars.registerPartial:

64
65
66
67
68
69
70
71
72
  }
};

var registerPartial = function(filename, content) {
  try {
    handlebars.registerPartial(filename, content);
  } catch (ex) {}
};

How to use handlebars.SafeString:

639
640
641
642
643
644
645
646
647
648
649
function homepageBuilder(page, completion, redirect) {
	var indexInfo = generateHtmlAndMetadataForFile(postsRoot + 'index.md');
	var footnoteIndex = 0;


	Handlebars.registerHelper('formatDate', function (date) {
		return new Handlebars.SafeString(new Date(date).format('{Weekday}<br />{d}<br />{Month}<br />{yyyy}'));
	});
	Handlebars.registerHelper('dateLink', function (date) {
		var parsedDate = new Date(date);
		return '/' + parsedDate.format("{yyyy}") + '/' + parsedDate.format("{M}") + '/' + parsedDate.format('{d}') + '/';

How to use handlebars.registerHelper:

427
428
429
430
431
432
433
434
435
436
let helperNames = Object.keys(HandlebarsHelpers);

// Register all helpers
for(let helperName of helperNames) {
    if(helperName.substr(-6) !== 'Helper') {
        Handlebars.registerHelper(
            helperName,
            HandlebarsHelpers[helperName]
        );
    } else {

How to use handlebars.compile:

474
475
476
477
478
479
480
481
482
483
  rule.collection.name += postfix;
  rule.provider += postfix;
}

rule = Object.assign(rule, overrides);
const ruleTemplate = Handlebars.compile(JSON.stringify(rule));
const templatedRule = JSON.parse(ruleTemplate({
  AWS_ACCOUNT_ID: process.env.AWS_ACCOUNT_ID,
  AWS_REGION: process.env.AWS_REGION,
  ...config,