I've found engines, plugins and functions to load external templates, but I'm wondering if there's a simpler way to do it. Something like this?
templates.html
<script id="testTemplate" type="text/html"> <div>this is a div</div> </script>
index.html
<div id="templateContainer"></div> <script> $(document).ready(function() { $("#templateContainer").load("templates.html"); } </script>
Will this work? Are there any "gotchas"?
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.
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.
Knockout is a fast, extensible and simple JavaScript library designed to work with HTML document elements using a clean underlying view model. It helps to create rich and responsive user interfaces.
KnockoutJS is basically a library written in JavaScript, based on MVVM pattern that helps developers build rich and responsive websites.
Here's what I use to load a template file that contains a collection of templates:
var loadTemplateCollection = function(file, success) { $.get('templates/' + file + '.html', function(templates) { $('body').append('<div style="display:none">' + templates + '<\/div>'); success(); }); };
Here's an example where I use this function:
self.loadPage = function () { if (!self.isLoaded()) { loadTemplateCollection('uploadwizard', function() { self.isLoaded(true); self.uploadWizard(); }); } }
Your view would look something like this (the if
is important):
<div data-bind="template: {'if': isLoaded, name: 'uploadwizard', data: wizard}"></div>
This is what I am using to load the new page view. I think it is pretty simple to use :
var template = 'template.html'; var targetID = 'container'; var partialVM = {data : 1}; var load = function (template, targetID, partialVM) { $.ajax(template, { async: false }) .success(function (stream) { $('#' + targetID).html(stream); ko.applyBindings(partialVM, document.getElementById(targetID)); } ); };
But in my html templates I didn't have the script element, just a simple div as root element.
I hope it helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With