Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A super basic template engine. This example builds a twitter feed list using a template string with placeholders.
<!DOCTYPE html>
<html>
<head>
<title>Basic templating</title>
</head>
<body>
<div id="tweet-list">
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script>
$.getJSON( "http://search.twitter.com/search.json?q=%23javascript&rpp=100&callback=?", {}, function( response ){
var stringTemplate = '<div class="tweet"><div class="tweet-created-date">{{created_at}}</div><div class="tweet-from_user">{{from_user}}</div><div class="tweet-from_user_id">{{from_user_id}}</div><div class="tweet-from_user_id_str">{{from_user_id_str}}</div><div class="tweet-from_user_name">{{from_user_name}}</div><div class="tweet-geo">{{geo}}</div><div class="tweet-id">{{id}}</div><div class="tweet-id_str">{{id_str}}</div><div class="tweet-iso_language_code">{{iso_language_code}}</div><div class="tweet-profile_image_url">{{profile_image_url}}</div><div class="tweet-profile_image_url_https">{{profile_image_url_https}}</div><div class="tweet-source">{{source}}</div><div class="tweet-to_user">{{to_user}}</div><div class="tweet-to_user_id">{{to_user_id}}</div><div class="tweet-to_user_id_str">{{to_user_id_str}}</div><div class="tweet-to_user_name">{{to_user_name}}</div><div class="tweet-text">{{text}}</div></div><hr />',
output = [],
results = response.results,
startMarker = '{{', endMarker = '}}',
key, value, i, parts, loops, tmplArray, part0,
console = window.console;
tmplArray = stringTemplate.split(startMarker);
loops = tmplArray.length;
for( key in results ){
if( results[key] instanceof Object ){
value = results[key];
output.push( tmplArray[0] );
for( i = 1; i < loops; i++ ){
parts = tmplArray[ i ].split(endMarker);
part0 = value[ parts[0] ];
if( part0 ){ output.push( part0 ); }
output.push( parts[1] );
}
}
}
$('#tweet-list').append( output.join('') );
} );
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.