Created
September 20, 2014 17:10
-
-
Save sbaldwin24/a6500a5d4711795a8fbc to your computer and use it in GitHub Desktop.
UnderscoreJS Demo Template
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> | |
<html lang="en"> | |
<head> | |
<title>User Profile Page</title> | |
<meta charset="utf-8"> | |
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.3.3/underscore-min.js"></script> | |
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.0/jquery-1.8.0.min.js "></script> | |
<script> | |
window.onload = initPage; | |
function initPage() { | |
// Declare all the variables. | |
var exampleValues = {}, | |
parsedTemplate = "", | |
// Get the template from the script block. | |
templateText = $('#profileTemplate').html(), | |
// Then we use Underscore's template function to compile it | |
// into a stand alone function that we can feed values to and | |
// get HTML output. | |
demoTemplate = _.template(templateText); | |
// Here, we grab the data, and put the results into exampleValues. | |
// I'm using .ajax instead of .getJSON so I can set 'async: false' | |
// for the demo; in production you'd be checking for async calls | |
// to return, but I wanted to keep the script simple. | |
$.ajax({url: "data/profiledata.json", async: false, dataType: "json", success: function(json) {exampleValues = json;}}); | |
// Finally, we call the demoTemplate function we created earlier, | |
// passing in the data we just retrieved, and then put the | |
// resulting HTML into the empty div. | |
parsedTemplate = demoTemplate(exampleValues); | |
$("#profileBlock").html(parsedTemplate); | |
} | |
</script> | |
</head> | |
<body> | |
<div id="profileBlock"></div> | |
<!-- Wrap the template in a script tag with type="text/template". | |
Since the browser doesn't recognize that type, it won't render | |
or process it, but will leave it for jQuery to grab the content --> | |
<script id="profileTemplate" type="text/template"> | |
<h1><%= header %></h1> | |
<h3>Name: <%= name %></h3> | |
<h3>Address: <%= address %></h3> | |
<h3>Phone: <%= phone %></h3> | |
<p>Interests: <%= interests %></p> | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment