Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
JavaScript Templating Example to show rendering techniques of JS data in HTML or XML formats.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
<title>JSON Transform</title>
<script type="text/javascript" src=""></script>
<script type="text/javascript" src=""></script>
<script type="text/javascript" src=""></script>
<link href="" rel="stylesheet"></link>
<script type="text/template" id="tpl-html">
<div class="well">
<table class="table">
<% _.each( target, function(i) {%>
<td><%= %></td>
<td><%= i.lastName %>, <%= i.firstName %></td>
<td><%= %></td>
<td><%= %></td>
<% }); %>
<script type="text/template" id="tpl-xml">
<% _.each( target, function(i) {%>
<id><%= %></id>
<last><%= i.lastName %></last>
<first><%= i.firstName %></first>
<email><%= %></email>
<phone><%= %></phone>
<% }); %>
var rawData = [
{id:1, firstName:"Homer", lastName:"Simpson", email:"", phone:"555-123-1234"},
{id:2, firstName:"Bart", lastName:"Simpson", email:"", phone:"555-123-2345"},
{id:3, firstName:"Marge", lastName:"Simpson", email:"", phone:"555-123-3456"},
{id:4, firstName:"Lisa", lastName:"Simpson", email:"", phone:"555-123-4567"},
{id:5, firstName:"Maggie", lastName:"Simpson", email:"", phone:"555-123-5678"} ];
function showJSONString() {
$("#output").html( "<pre>" + JSON.stringify(rawData) + "</pre>") ;
function generateHTML() {
var data = { target:rawData };
var template = _.template( $("#tpl-html").text() );
$("#output").html( template(data) );
function generateXML() {
var data = { target:rawData };
var template = _.template( $("#tpl-xml").text() );
var xml = template(data);
$("#output").html( "<pre>" + _.escape( xml ) + "</pre>" );
<body style="padding:50px 10px ">
<div class="navbar navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a href="javascript:showJSONString()" class="btn" id="json">Show JSON String</a>
<a href="javascript:generateHTML()" class="btn" id="html">Generate HTML</a>
<a href="javascript:generateXML()" class="btn" id="xml">Generate XML</a>
<div id="output">Click a button above to transform the raw JS data.</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment