简体   繁体   中英

Twig not working the same as php

Why is it that when I write my test in php…

foreach ($rounds as $round){
    $assignment = $em->getRepository(‘WorkBundle:Doc’)->findOneBy(array(
        ‘user’ => $user->getId(),
        ’whichRound’ => $round,
    ));

   if (!$assignment){
    echo “assign ”.$round. “ to user”;
   }else{
    echo “already assigned to ”.$round. “ to user”;
   }
 }

return array (
    'user' =>  $user,
    'assignment' => $assignment,
    'rounds' => $rounds,
);

…it works correctly. When assignment is null, it will output the “assign ”.$round. “ to user”; “assign ”.$round. “ to user”; and when it's not null it will output “already assigned to ”.$round. “ to user”; “already assigned to ”.$round. “ to user”; .

However when I go in my twig template with the returned variables above and do…

{% for round in rounds %}
    {% if assignment is null %}
        <h2>{{ user }} successfully added to {{ round }}</h2>
    {% else %}
        <h2>{{ user }} has already been assigned to the {{ round }}</h2>
    {% endif %}
{% endfor %}

…it does not work correctly? It will instead output the same message twice…in an example, if the first round is null and the second one it not null, it will output the second message {{ user }} has already been assigned to the {{ round }} twice.

What am I messing up?

When you go through the foreach loop in your code, you're setting $assignment each time. When you return the array, you're only returning the last time $assignment is set.

It looks like $rounds is an array of numbers and you'd like to associate the round with an assignment result. Based on that, I'd advise building a new array like this:

$results = array();

foreach ($rounds as $round) {
    $row = array(
        'round' => $round,
        'assignment' => $em->getRepository('WorkBundle:Doc')->findOneBy(array(
            'user' => $user->getId(),
            'whichRound' => $round,
        ))
    );

    if ($row['assignment']) {
        echo "Already assigned $round to user.";
    } else {
        echo "Assign $round to user.";
    }

    $results[] = $row;
}

return array(
    'user' => $user,
    'results' => $results,
);

Your Twig template would then look like this:

{% for row in results %}
    {% if row.assignment is null %}
        <h2>{{ user }} successfully added to {{ row.round }}</h2>
    {% else %}
        <h2>{{ user }} has already been assigned to the {{ row.round }}</h2>
    {% endif %}
{% endfor %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM