Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix macro changing context in loop #773

Merged
merged 2 commits into from
Sep 14, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/twig.logic.js
Original file line number Diff line number Diff line change
Expand Up @@ -1006,7 +1006,8 @@ module.exports = function (Twig) {
state.macros[token.macroName] = function (...args) {
// Pass global context and other macros
const macroContext = {
...context,
// Use current state context because state context includes current loop variables as well
...state.context,
_self: state.macros
};
// Save arguments
Expand Down
6 changes: 6 additions & 0 deletions test/templates/macro-context-loop.twig
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{% macro make_me_smile(name, slang) %}{{ slang }} {{ name }}{% endmacro %}
{% import _self as greet %}
{% for greeting in greetings %}
{{ greet.make_me_smile('Twigjs', greeting) }}
{{ greeting }}
{% endfor %}
10 changes: 10 additions & 0 deletions test/test.macro.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,16 @@ describe('Twig.js Macro ->', function () {
twig({ref: 'import-macro-context-self'}).render({greetings: 'Howdy'}).trim().should.equal('Howdy Twigjs');
});

it('it should run wrapped macro in loop without mutating state context', function () {
twig({
id: 'import-macro-context-loop',
path: 'test/templates/macro-context-loop.twig',
async: false
});
// Load the template
twig({ref: 'import-macro-context-loop'}).render({greetings: ['Howdy', 'Hey']}).trim().should.equal('Howdy Twigjs\nHowdy\nHey Twigjs\nHey');
});

it('it should run wrapped macro with default value for a parameter and self reference', function () {
twig({
id: 'import-macro-defaults-self',
Expand Down