Skip to content

Commit

Permalink
{% include %} tag accepts variable
Browse files Browse the repository at this point in the history
if that variable is an object with `render()` it is assumed
to be a template.

see django/django@5cdacbd
  • Loading branch information
oberhamsi committed Mar 14, 2014
1 parent 0a4141f commit 98481c9
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 3 deletions.
4 changes: 4 additions & 0 deletions docs/tags.md
Original file line number Diff line number Diff line change
Expand Up @@ -428,6 +428,10 @@ the variable ``template_name``:

{% include template_name %}

The variable may also be an object with a `render()` method that
accepts a context. This allows you to reference a compiled `Template` in
your context.

An included template is rendered with the context of the template that's
including it. This example produces the output ``"Hello, John"``:

Expand Down
9 changes: 6 additions & 3 deletions lib/tag/loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,14 @@ IncludeNode.prototype.getByType = Node.prototype.getByType;

IncludeNode.prototype.render = function(context) {
if (typeof(this.templatePath) === 'string') {
var templateName = this.templatePath;
var template = this.templatePath;
} else {
var templateName = this.templatePath.resolve(context);
var template = this.templatePath.resolve(context);
}
// does this quack like a Template?
if (typeof(template.render) !== 'function') {
template = this.env.getTemplate(template);
}
var template = this.env.getTemplate(templateName);
// render
var values = {};
for (var key in this.extraContext) {
Expand Down
10 changes: 10 additions & 0 deletions test/basic.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,16 @@ var TestObj = function() {
return this;
}

exports.testIncludeTemplateArgument = function() {
// any object having render() can be included as template
var ctx = {
tmpl: new Template('This worked!')
};
var outerTmpl = new Template('{% include tmpl %}');
var output = outerTmpl.render(ctx);
assert.equal(output, 'This worked!');

}
exports.testBasic = function() {

// register fake template loader for `include` testing later on
Expand Down

0 comments on commit 98481c9

Please sign in to comment.