Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I combine templates from different HTML files

Tags:

knockout.js

Since Knockout's individual templates are kept in script tags, I thought that I could set the src attribute of the tag and load the HTML from a separate file. Doing so naïvely simply didn't work, so either

  1. There's some trick to getting the binding of templates to work with src tag that I need to use
  2. There's a different way to load templates from different files

(The other two possibilities -- 3, all the programmers on this project are expected to modify the same gigantic file, which will be loaded by the browser on start-up, and 4, don't use Knockoutjs for anything larger than a toy project -- I consider equivalent.)

like image 527
Michael Lorton Avatar asked May 01 '12 18:05

Michael Lorton


People also ask

How do you add templates in your HTML?

You can use the <template> tag if you have some HTML code you want to use over and over again, but not until you ask for it. To do this without the <template> tag, you have to create the HTML code with JavaScript to prevent the browser from rendering the code.


1 Answers

A browser won't respond to src on anything that has a type other than one of the various 'javascript' types and with those it will try to execute the result as a script.

Several options though:

  • use a template engine that can pull templates remotely (the best one is here: https://github.com/ifandelse/Knockout.js-External-Template-Engine).
  • Loop on your script tags that contain templates and load them up. Something like this would pull the contents using the src as the location. You would need to be careful of when you call applyBindings, if your templates aren't ready.

    $("script[type='text/html']").each(function(index, el) { $.get($(el).attr("src"),
        function(response) {
            $(el).text(response); });
    }); 
    
  • Here are some other options that I looked at for doing this a while back: http://www.knockmeout.net/2011/03/using-external-jquery-template-files.html

like image 71
RP Niemeyer Avatar answered Oct 16 '22 12:10

RP Niemeyer