如何在树枝中显示布尔值

how to display a boolean values in twig

在此 table 中,我想在 "reponse" 字段中显示 "yes" 或 "no" 而不是“1”和“ ” 这是我 table 的图片: 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

您可以添加 if 语句 {% if TypeQuestion.reponse %}yes{% else %}no{% endif%}

这是我通常做的事情:

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

参考:http://twig.sensiolabs.org/doc/templates.html#other-operators

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

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

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

例如:

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

这样您就可以在不更改模板的情况下轻松处理新的可能性和新的语言。