Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an external Template in KnockoutJS

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.

like image 565
KebdnK Avatar asked Feb 28 '12 11:02

KebdnK


People also ask

How does Ko identify the template block that needs to be rendered?

Shorthand syntax: If you just supply a string value, KO will interpret this as the ID of a template to render. The data it supplies to the template will be your current model object.

How do you activate a KnockoutJS model?

To activate Knockout, add the following line to a <script> block: ko. applyBindings(myViewModel); You can either put the script block at the bottom of your HTML document, or you can put it at the top and wrap the contents in a DOM-ready handler such as jQuery's $ function.

How do I use knockout js in HTML?

It is very easy to use KnockoutJS. Simply refer the JavaScript file using <script> tag in HTML pages. A page as in the following image will be displayed. Click on download link and you will get the latest knockout.


1 Answers

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/

like image 162
soniiic Avatar answered Sep 28 '22 07:09

soniiic