Skip to content

Instantly share code, notes, and snippets.

@andersdn
Last active January 29, 2017 06:48
Show Gist options
  • Save andersdn/4b03c7253fdfc19827d7 to your computer and use it in GitHub Desktop.
Save andersdn/4b03c7253fdfc19827d7 to your computer and use it in GitHub Desktop.
Basic (jquery) ajax template loading for underscore js
<html>
<body>
<h1>Foo is <%= foo %></h1>
<% _.each(baz,function(value,index){ %>
<h2>Baz <%= index %> is <%= value %>
<h2>
<% }) %>
</body>
</html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="main.js"></script>
</head>
<body>
<div id="container"></div>
</body>
</html>
// underscore template loader
function _tpl(templateName,callback) {
var tmpl_url = '_tlp-' + templateName + '.html';
$.ajax({
url: tmpl_url,
method: 'GET',
async: false,
contentType: 'text',
success: function (data) {
callback(data);
}
});
}
$(document).ready(function(){
var template_data = {
'foo':'bar',
'baz':['apple','bananna','custard']
};
_tpl('dashboard',function(template){
var tpl = _.template(template);
$("#container").html(tpl(template_data));
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment