簡體   English   中英

樹枝不工作與PHP相同

[英]Twig not working the same as php

為什么當我用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,
);

…它正常工作。 當assignment為null時,將輸出“assign ”.$round. “ to user”; “assign ”.$round. “ to user”; 當它不為null時,將輸出“already assigned to ”.$round. “ to user”; “already assigned to ”.$round. “ to user”;

但是,當我使用上面返回的變量進入樹枝模板並執行...

{% 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 %}

…無法正常工作? 相反,它將輸出兩次相同的消息…在一個示例中,如果第一輪為null,第二輪不為null,它將輸出第二條消息{{ user }} has already been assigned to the {{ round }}兩次。 。

我搞砸了嗎?

當您遍歷代碼中的foreach循環時,每次都在設置$assignment 返回數組時,僅返回最后一次設置$assignment時間。

看起來$rounds是一個數字數組,您想將回合與賦值結果相關聯。 基於此,我建議構建一個像這樣的新數組:

$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,
);

您的Twig模板將如下所示:

{% 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 %}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM