繁体   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