Created
September 22, 2010 21:28
-
-
Save jboesch/592616 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> | |
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> | |
<head> | |
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> | |
<title>Mustache JS - Template in script block instead of js variable</title> | |
<script type="text/javascript" src="http://github.com/janl/mustache.js/raw/master/mustache.js"></script> | |
</head> | |
<body> | |
<script type="text/javascript"> | |
// This is kind-of a hybrid between John Resig's micro-templating | |
// http://ejohn.org/blog/javascript-micro-templating/ and the templating awesomeness from Mustache.js | |
// http://github.com/janl/mustache.js | |
// | |
// Create an extension of Mustache to allow us to grab the content from | |
// a script block in the HTML below | |
// Don't worry, the browser hits the <script type="text/html"> and doesn't know how to render it, so it | |
// will never display :) | |
Mustache.block_id_to_html = function(){ | |
var el = document.getElementById(arguments[0]); | |
arguments[0] = el && el.innerHTML || arguments[0]; | |
return this.to_html.apply(this, arguments); | |
} | |
// When the page is loaded, snag the template code stored in id="user_tmpl" below | |
// and run the replacements, words the same as Mustache.to_html(my_tmpl, {}) | |
// only we're just storing the my_tmpl variable in the HTML instead of a js variable | |
window.onload = function(){ | |
var replacements = { | |
list: { | |
people: [{ name: 'john', age: 33 }, { name: 'bill', age: 54 }] | |
} | |
}; | |
var html_m = Mustache.block_id_to_html('user_tmpl', replacements); | |
alert(html_m); | |
}; | |
</script> | |
<script type="text/html" id="user_tmpl"> | |
{{#list}} | |
<ul> | |
{{#people}} | |
<li>{{ name }} - {{ age }}</li> | |
{{/people}} | |
</ul> | |
{{/list}} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment