0

I've read that you can set a variable inside of a loop, and set that same variable outside of the loop with "" to be able to use it outside of the loop. Although when attempting this, it is not working for me. Here is the code I am using (simplified for the purpose of troubleshooting):

{% requireLogin %}

{% if currentUser == user.username %}

{# -- Set Excludes Expenses here as well, to use out of the loop -- #}
{% set excludedExpenses = "" %}

    Excluded Expenses (Outside Loop): {{ excludedExpenses }}<br />

    <p>{{ dump(excludedExpenses) }}</p>

    {# -- Get All Expense Entries -- #}
    {% set userExpenses = craft.entries.section('expenses').authorId(currentUser.id).limit(null) %}

        {# --- Excluded Expenses Loop -- #}
        {% for expense in userExpenses if expense.excludeExpense.contains('Temporarily Exclude') %}
            {% set excludedExpenses = expense.expenseName %}

            Excluded Expenses (Inside Loop): {{ excludedExpenses }}

            <p>{{ dump(excludedExpenses) }}</p> 

        {% endfor %}
        {# -- End Excluded Expenses Loop -- #}  

{% endif %}

This is the result - http://cl.ly/image/1Z2Q2r2Q102s

The variable is only being recognized and displayed inside of the loop. The actual variable I will use (beyond this simple test) is an integer. I tested with an integer variable and that failed also, so I am not sure if that would change anything for this example. Thanks in advance for any help you can give! :)

3

Your dump from outside the loop is being dumped BEFORE the variable is set within the loop. Move it to after the loop and try it again.

  • Rick, that makes total sense, and I can't believe I missed that. Thank you! :) – Angela Sep 2 '15 at 21:03
  • It's the simple things that trip us all up. – Rick Sep 2 '15 at 21:05
  • Ha - exactly! :) – Angela Sep 2 '15 at 21:06
1

The output looks like what I'd expect it to be based on the code sample.

You're saying that if you put:

 Excluded Expenses (After Loop): {{ excludedExpenses }}

...AFTER the end of the loop, it doesn't display 'Pets'?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.