Using an external Template in KnockoutJS

KebdnK picture KebdnK · Feb 28, 2012 · Viewed 16.3k times · Source

is it possible to use an external Template in KnockoutJS like this?

<script type="text/html" id="a_template" src="templates/a_template.html">
</script>

I've tried this solution but didn't get it working.

Answer

soniiic picture soniiic · Feb 28, 2012

You can use jquery to dynamically load html into a script element, and then execute knockout based on that.

<script type="text/html" id="template_holder"></script>
<script type="text/javascript">
$('#template_holder').load('templates/a_template.html', function() {
  alert('Load was performed.');
  //knockout binding goes here
});</script>

Your knockout binding must be done in the callback function though, otherwise there's a chance that you'll be trying to bind before the page has loaded

UPDATE Here's an example I've coded on jsfiddle to demonstrate dynamic loading: http://jsfiddle.net/soniiic/2HxPp/