【问题标题】:Twig not working the same as phpTwig 的工作方式与 php 不同
【发布时间】:2016-12-20 14:23:15
【问题描述】:

为什么当我用 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,
);

…它工作正常。赋值为null时输出“assign ”.$round. “ to user”;,不为null时输出“already assigned to ”.$round. “ to user”;

但是,当我使用上面返回的变量进入我的 twig 模板并执行...

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

……它不能正常工作?相反,它将输出相同的消息两次……例如,如果第一轮为空,第二轮不为空,它将输出第二条消息{{ user }} has already been assigned to the {{ round }} 两次。

我在搞砸什么?

【问题讨论】:

    标签: php for-loop twig logic


    【解决方案1】:

    当您在代码中执行 foreach 循环时,您每次都在设置 $assignment。当您返回数组时,您只会返回 last 设置 $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 %}
    

    【讨论】:

      猜你喜欢
      • 2017-01-14
      • 2020-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-01
      • 1970-01-01
      相关资源
      最近更新 更多