Skip to content

Commit

Permalink
Update parent context when extending a template (#369)
Browse files Browse the repository at this point in the history
* Add failing test for extending context

* Add extend() function to extend a JS object with another

* Fix issue with extends not pushing to context
  • Loading branch information
dave-irvine committed May 14, 2016
1 parent 17bcbc1 commit af38035
Show file tree
Hide file tree
Showing 5 changed files with 50 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/twig.lib.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,19 @@ module.exports = function(Twig) {
return target;
};

Twig.lib.extend = function (src, add) {
var keys = Object.keys(add),
i;

i = keys.length;

while (i--) {
src[keys[i]] = add[keys[i]];
}

return src;
};

Twig.lib.replaceAll = function(string, search, replace) {
return string.split(search).join(replace);
};
Expand Down
15 changes: 15 additions & 0 deletions src/twig.logic.js
Original file line number Diff line number Diff line change
Expand Up @@ -599,12 +599,27 @@ module.exports = function (Twig) {
return token;
},
parse: function (token, context, chain) {
var template,
innerContext = Twig.ChildContext(context);
// Resolve filename
var file = Twig.expression.parse.apply(this, [token.stack, context]);

// Set parent template
this.extend = file;

if (file instanceof Twig.Template) {
template = file;
} else {
// Import file
template = this.importFile(file);
}

// Render the template in case it puts anything in its context
template.render(innerContext);

// Extend the parent context with the extended context
Twig.lib.extend(context, innerContext);

return {
chain: chain,
output: ''
Expand Down
6 changes: 6 additions & 0 deletions test/templates/extendee.twig
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{% macro macro() %}ok!{% endmacro %}
{% import _self as my %}

{% block content %}
<p>Sub: content</p>
{% endblock %}
5 changes: 5 additions & 0 deletions test/templates/extender.twig
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{% extends 'extendee.twig' %}

{% block content %}
{{ my.macro({}) }}
{% endblock %}
11 changes: 11 additions & 0 deletions test/test.extends.js
Original file line number Diff line number Diff line change
Expand Up @@ -142,4 +142,15 @@ describe("Twig.js Extensions ->", function() {
var result = twig({data:"{% noop %}"}).render();
result.should.equal("noop2");
});

it("should extend the parent context when extending", function() {
var template = twig({
path: 'test/templates/extender.twig',
async: false
});

var output = template.render();

output.trim().should.equal("ok!");
});
});

0 comments on commit af38035

Please sign in to comment.