Created
June 19, 2012 19:08
-
-
Save matthewp/2955953 to your computer and use it in GitHub Desktop.
Synchronous loading of templates in a link tag.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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; | |
} | |
} | |
}); | |
})(); |
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 }}
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
This looks extremely useful, good alternative to using require.js text plugin to handle remote templates.
Note for anyone stumbling onto this: HN thread.