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

UnusedVariable: Variables defined inside for should not be usable outside #181

Open
sustmi opened this issue Jul 2, 2021 · 1 comment
Open
Labels

Comments

@sustmi
Copy link

sustmi commented Jul 2, 2021

In the current Twig documentation there is a note about variable scope defined inside for loops:

Note that loops are scoped in Twig; therefore a variable declared inside a for loop is not accessible outside the loop itself:

{% for item in list %}
    {% set foo = item %}
{% endfor %}

{# foo is NOT available #}

If you want to access the variable, just declare it before the loop:

{% set foo = "" %}
{% for item in list %}
    {% set foo = item %}
{% endfor %}

https://twig.symfony.com/doc/3.x/tags/set.html

However, when I try to run twigcs on the following code:

{% for item in list %}
    {% set foo = item %}
{% endfor %}

{{ foo }}

it does not consider foo variable inside the loop to be unused.

Steps to reproduce

I created a failing test case (that should be passing) here: https://github.com/sustmi/twigcs/blob/19819daad7900dce0f18c4569b9f9fec539cdf11/tests/Twig3FunctionalTest.php#L231

  1. git clone https://github.com/sustmi/twigcs/
  2. cd twigcs
  3. git checkout unused-variable-issue-181
  4. composer install
  5. phpunit tests/Twig3FunctionalTest.php
sustmi added a commit to sustmi/twigcs that referenced this issue Jul 2, 2021
@OwlyCode OwlyCode added the bug label Aug 27, 2021
@gnutix
Copy link

gnutix commented May 29, 2022

In the same vein but maybe different :

{% set was_current = false %}

{% for item in items %}
    {% if not loop.first and not was_current and not item.current %}
        {# ... #}
    {% endif %}

    {# ... #}

    {% set was_current = item.current %}
{% endfor %}

Produces an inspection for the line {% set was_current = item.current %} :

WARNING Unused variable "was_current"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants