Peter Wone Peter Wone - 1 year ago 55
HTML Question

Why doesn't src work for templates?

The HTML script tag can be used to define named templates:

<script type="text/html" id="Lookup">
<label class="field-title" data-bind="text: Metadata.FieldTitle, css: { hasError: !IsValid() }"></label>
<div data-bind="html: Metadata.FieldIntro"></div>
<select class="form-control" data-bind="attr: { id: 'ff' + Metadata.FormFieldID }, options: Lookup, optionsText: 'Caption', optionsValue: 'Id', optionsCaption: Metadata.FieldIntro || 'Select an item...', value: Value, css: { hasError: !IsValid() }"></select>

According to MDN and msdn, I should be able to move the content of a template into a file and reference it like this:

<script type="text/html" id="Lookup" src="Lookup.html"></script>

According to Fiddler template files are being loaded (I have several). What stops knockout from using the templates when they aren't inline, and is there anything that can be done about it?

From the comments, script tags don't parse what they load into the DOM. I could use something like jQuery ajax to load, parse and inject but knockout uses the script node's id to reference the template, so the next question is how to make visible the fragment so loaded.

At a stab I surmise that I need to do something like this:

.append("<div id='Lookup' style='display:none'></div>")
.load("Templates/Lookup.html" );

Close, but no cigar. Here it is corrected and wrapped up as a function:

function loadTemplate(name) {
$(document.body).append("<div id='" + name + "' style='display:none'></div>");
$("#" + name).load("Templates/" + name + ".html");

Knockout happily uses the template.

Answer Source

Browsers don't know how to process programs written in text/html (yes, that sentence doesn't make a whole lot of sense, this is a hack you are using).

Whatever JavaScript you are using to process the templates is reading the childnodes of the script element in the DOM. It hasn't been written to check for a src attribute and load external content.