Skip to content

feat: add FOREACH_LOCALISE option to scope loop variables#419

Open
toddr-bot wants to merge 1 commit into
mainfrom
koan.toddr.bot/fix-foreach-localise
Open

feat: add FOREACH_LOCALISE option to scope loop variables#419
toddr-bot wants to merge 1 commit into
mainfrom
koan.toddr.bot/fix-foreach-localise

Conversation

@toddr-bot

Copy link
Copy Markdown
Contributor

What

Add a FOREACH_LOCALISE configuration option that restores the loop iterator variable to its pre-loop value after FOREACH exits.

Why

Fixes GH #317. Currently FOREACH x = list leaves x set to the last iteration value after the loop — inconsistent with Perl's foreach which localizes the iterator. This surprises users coming from Perl.

Making this unconditional would break backward compatibility (some code relies on reading the variable after the loop, e.g. with LAST), so this is opt-in via a config option.

How

  • Save/restore the target variable alongside the existing loop save/restore in Directive::foreach()
  • Config flows through Template->new()ParserDirective factory
  • Also available globally via $Template::Directive::FOREACH_LOCALISE
  • Default is off (preserving historical behavior)

Testing

  • 5 new tests in t/foreach-localise.t covering: basic restore, undef initial value, nested loops, hash variables, postfix form
  • All 2905 existing tests pass unchanged (backward compatibility confirmed)

🤖 Generated with Claude Code

Add a FOREACH_LOCALISE configuration option that causes FOREACH loops
with named target variables to save and restore the target variable's
value after the loop exits, matching Perl's foreach behavior.

Without this option (the default), the loop variable retains its last
iteration value after the loop — the historical TT2 behavior.

With FOREACH_LOCALISE => 1:
  [% x = 'original' %]
  [% FOREACH x = [1, 2, 3] %]...[% END %]
  [% x %]  =>  'original'  (not '3')

The option can be set per-template via Template->new() or globally
via $Template::Directive::FOREACH_LOCALISE.

Fixes GH #317.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@toddr-bot

Copy link
Copy Markdown
Contributor Author

Recreated from #346 (auto-closed when the toddr-bot fork was removed). Original branch is now hosted on this repo.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant