如何在twig中显示布尔值

问题描述 投票:0回答:3

在此表中,我想在“响应”字段中显示“是”或“否”而不是“1”和“” 这是我的桌子的图片: this picture shows my table :

我正在使用 symfony2.8,在我的实体“typeQuestion”中我有这个:

/**
 * @var boolean
 * @ORM\Column(name="reponse", type="boolean")
 */

private $reponse;


/**
 * Set reponse
 *
 * @param boolean $reponse
 * @return TypeQuestion
 */
public function setReponse($reponse)
{
    $this->reponse = $reponse;

    return $this;
}

/**
 * Get reponse
 *
 * @return boolean 
 */
public function getReponse()
{
    return $this->reponse;
}
 public function __toString() {
    return $this->libelle;
}

}

以我的形式:

 ->add('reponse', 'choice', array(
                'label' => 'Reponse',
                'choices' => array("true" => 'Oui', false => 'Non'),
                'expanded' => true,
                'multiple' => false,
                'required' => true
            ));
}

我认为:

 <td class="center">{{TypeQuestion.libelle}}</td>
<td class="center">{{TypeQuestion.description}}</td> 
<td class="center">{{TypeQuestion.reponse}}</td> 

在 phpmyadmin 中,这就是我得到的: 在 phpmyadmin 中,这就是我得到的:2

symfony boolean field
3个回答
56
投票

这是我通常做的事情:

{{ someBoolean ? 'Yes' : 'No' }}

参考:https://twig.symfony.com/doc/3.x/templates.html#other-operators


10
投票

可以添加if语句

{% if TypeQuestion.reponse %}yes{% else %}no{% endif%}


2
投票

尽管接受的答案是有效的,但我认为它不是很通用。想象一下,您在数百个模板中打印此内容,并且希望随着时间的推移更改标签。

您将必须更新所有模板,如果您的应用程序支持多语言……

最好的做法是翻译您的文本。

例如:

{% if TypeQuestion.reponse %}
  {{ 'answer.true' | trans({}, 'your_trans_catalog') }}
{% else %}
  {{ 'answer.false' | trans({}, 'your_trans_catalog') }}
{% endif%}

通过这种方式,您可以轻松处理新的可能性和新语言,而无需更改模板。

© www.soinside.com 2019 - 2024. All rights reserved.