Last active
August 29, 2015 14:02
-
-
Save torgeir/9109d2eaccd9bd450cc8 to your computer and use it in GitHub Desktop.
Hogan custom function access nested context
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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) { | |
// cannot access "site" (parent context) | |
// only the current "section" (context) as `this` | |
console.log(this); | |
// pass 1: Object {title: "Section 1"} | |
// pass 2: Object {title: "Section 2"} | |
// pass 3: Object {title: "Section 3"} | |
// tmpl is "{{heading}}" | |
// but there is no way to look up heading from "site" | |
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 - </li> | |
// <li>Section 2 - </li> | |
// <li>Section 3 - </li> | |
// </ul> | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment