Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save torgeir/7064a68fd253755f64a3 to your computer and use it in GitHub Desktop.
Save torgeir/7064a68fd253755f64a3 to your computer and use it in GitHub Desktop.
Hogan custom function access nested context -- like hogan does internally
<!doctype html>
<meta charset=utf-8>
<title>hogan custom function access nested context</title>
<script src="hogan-3.0.1.js"></script>
<script>
var data = {
site: {
heading: "Site heading",
sections: [
{ title: "Section 1" },
{ title: "Section 2" },
{ title: "Section 3" }
],
},
custom: function () {
return function (tmpl, contexts) {
function lookup (key, contexts) {
var i = contexts.length;
while (i-- > 0) {
var context = contexts[i];
var value = context[key];
if (typeof value !== "undefined") {
return value;
}
}
return key;
}
var match = /{{(.*)}}/.exec(tmpl);
var key = match[1];
if (match && key) {
return lookup(key, contexts);
}
return tmpl;
}
}
};
var template = [
"{{#site}}",
"<h1>{{heading}}:</h1>",
"<ul>",
"{{#sections}}",
"<li>{{title}} - {{#custom}}{{heading}}{{/custom}}</li>",
"{{/sections}}",
"</ul>",
"{{/site}}"
].join('');
var html = Hogan.compile(template).render(data);
console.log(html);
// <h1>Site heading:</h1>
// <ul>
// <li>Section 1 - Site heading</li>
// <li>Section 2 - Site heading</li>
// <li>Section 3 - Site heading</li>
// </ul>
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment