Reputation: 9555
In the following code why does the jquery template not render? I thought that the template was build in? thank you
<script id="friendsTemplate" type="text/html">
<ul>
{{each(index,friend) friends}}
<li>${ friend.name }</li>
{{/each}}
</ul>
</script>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/knockout-2.2.1.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>details</h1>
<p>first name: <input data-bind="value: firstName" /></p>
<p>last name: <input data-bind="value: lastName" /></p>
<p>full name: <span data-bind ="text: fullName"></span></p>
<h2>friends</h2>
<div data-bind="template: 'friendsTemplate'"></div>
<script id="friendsTemplate" type="text/html">
<ul>
{{each(index,friend) friends}}
<li>${ friend.name }</li>
{{/each}}
</ul>
</script>
</div>
</form>
</body>
</html>
<script type ="text/javascript">
function friend(name) {
return {
name: ko.observable(name)
};
}
var viewModel ={
firstName: ko.observable("bert"),
lastName: ko.observable("smith"),
friends:ko.observableArray([new friend('steve'),new friend('annie')])
};
viewModel.fullName = ko.dependentObservable(function () {
return this.firstName() + " " + this.lastName();
},viewModel);
ko.applyBindings(viewModel);
</script>
Upvotes: 0
Views: 2435
Reputation: 139798
The jQuery.tmpl support is built in however you need to reference jQuery and the jQuery.tmpl to make it work as stated in the documentation under: Note 6: Using jQuery.tmpl, an external string-based template engine:
By default, Knockout comes with support for jquery.tmpl. To use it, you need to reference the following libraries, in this order:
<!-- First jQuery --> <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<!-- Then jQuery.tmpl --> <script src="jquery.tmpl.js"></script>
<!-- Then Knockout --> <script src="knockout-x.y.z.js"></script>
If you reference all the dependencies your code should work fine: Demo JSFiddle
Upvotes: 4
Reputation: 221
You need to pass a data object to your template.
data-bind="template: { name: 'friendsTemplate', data: $data }"
Look at http://knockoutjs.com/documentation/template-binding.html for details.
Is there a reason why you are using a jQuery Template? The following is more in alignment with "typical" Knockout usage. Also you should only use external templates if there is reuse. This code could easily be inlined.
<script id="friendsTemplate" type="text/html">
<ul data-bind="friends">
<li data-bind="text: name"></li>
</ul>
</script>
Upvotes: 1