Php 使用变量获取对象
我在数据库和一个实体中有两个属性:Php 使用变量获取对象,php,symfony,twig,Php,Symfony,Twig,我在数据库和一个实体中有两个属性: title_one title_two 在模板(细枝)中,我只希望从这些字段中获取一个 {% set type = 'two' %} 我可以: <div id="title"> {% if type == 'one' %} {% entity.title_one %} {% elseif type == 'two' %} {% entity.title_two %} {% endif %} </div> {%if
title_one
title_two
在模板(细枝)中,我只希望从这些字段中获取一个
{% set type = 'two' %}
我可以:
<div id="title">
{% if type == 'one' %}
{% entity.title_one %}
{% elseif type == 'two' %}
{% entity.title_two %}
{% endif %}
</div>
{%if type='one%}
{%entity.title_one%}
{%elseif type=='2'%}
{%entity.title_two%}
{%endif%}
它工作得很好,但我想这样做:
<div id="title">
{{ entity.title_{{ type }} }}
</div>
{{entity.title{{{type}}
如何创建它?只需向实体添加一个helper方法,类似于
getMyType()
。这将返回正确的类型。在细枝模板中,可以访问以下方法:
{%set type==myEntity.getMyType()%}
请注意,您必须将实体注入控制器中的模板中:
$Response=$this->render(
“MySomethingBundle:Area:page.html.twig”,
数组('myEntity'=>$entityInstance));
顺便说一下,您可能想看看。只需向实体添加一个helper方法,类似于
getMyType()
。这将返回正确的类型。在细枝模板中,可以访问以下方法:
{%set type==myEntity.getMyType()%}
请注意,您必须将实体注入控制器中的模板中:
$Response=$this->render(
“MySomethingBundle:Area:page.html.twig”,
数组('myEntity'=>$entityInstance));
顺便说一句,您可能想看一看。尝试使用以下方法:
{{ attribute(entity, "title_" ~ type) }}
请尝试使用以下方法:
{{ attribute(entity, "title_" ~ type) }}
你的问题有点不清楚:
title\u one
和title\u two
是独立的实体,还是同一实体的属性?对不起,它们是同一实体的属性。你的问题有点不清楚:title\u one
和title\u two
是独立的实体,还是同一实体的属性?对不起,它们是同一实体的属性。