Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.