Skip to content

Instantly share code, notes, and snippets.

@matthewp
Created June 19, 2012 19:08
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matthewp/2955953 to your computer and use it in GitHub Desktop.
Save matthewp/2955953 to your computer and use it in GitHub Desktop.
Synchronous loading of templates in a link tag.
(function() {
"use strict";
Object.defineProperty(HTMLLinkElement.prototype, 'template', {
get: function() {
if(!/template/i.test(this.rel)) {
return "";
}
var req = new XMLHttpRequest();
req.open('GET', this.href, false);
req.setRequestHeader('Accept', this.type || "*/*");
req.send();
if(req.status !== 200) {
throw "Unable to retrieve the template.";
} else {
return req.responseText;
}
}
});
})();
@jdp
Copy link

jdp commented Jun 19, 2012

This looks extremely useful, good alternative to using require.js text plugin to handle remote templates.

Note for anyone stumbling onto this: HN thread.

@GeorgeNava
Copy link

This would be perfect as a jQuery plugin like:

$('#body').render('myblog.html',data)

Where the render method could use your snippet to grab the template string and parse it with the data object, then attach the result to the element specified.

It would be perfect if it used the django/jinja template style of {% statement %} and {{ var | filter }}

@matthewp
Copy link
Author

This is template engine agnostic, intentionally. You can you any style you prefer, all this does is fetch the template from a link tag.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment