Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load knockout template from external file without complex engine?

Tags:

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"?

like image 769
THE JOATMON Avatar asked Jun 12 '13 19:06

THE JOATMON


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 I use KnockoutJS 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.

What is a knockout file?

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.

What is KnockoutJS used for?

KnockoutJS is basically a library written in JavaScript, based on MVVM pattern that helps developers build rich and responsive websites.


2 Answers

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> 
like image 189
Michael Best Avatar answered Oct 23 '22 15:10

Michael Best


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.

like image 41
Damien Avatar answered Oct 23 '22 16:10

Damien