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
src
tag that I need to use(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.)
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.
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:
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
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