【发布时间】:2015-07-14 09:32:23
【问题描述】:
我正在用 Twig 构建一个显示用户数据的页面;数据来自用户和配置文件实体(您可以从用户访问)。
为避免在变量为 null 时页面显示错误,我必须检查是否定义了每个变量(如您所见,这会使代码变得更重)。
<dt>firstname:</dt>
{% if user.firstname is defined %}
<dd>{{ user.firstname|title }}</dd>
{% endif %}
<dt>lastname:</dt>
{% if user.lastname is defined %}
<dd>{{ user.lastname|title }}</dd>
{% endif %}
<dt>Email address:</dt>
{% if user.lastname is defined %}
<dd>{{ user.email|title }}</dd>
{% endif %}
<dt>Birthday:</dt>
{% if user.profile.birthday is defined %}
<dd>{{ user.profile.birthday|date("d M y") }}</dd>
{% endif %}
<dt>Mobile phone:</dt>
{% if user.profile.mobilePhone is defined %}
<dd>{{ user.profile.mobilePhone }}</dd>
{% endif %}
<dt>Landline:</dt>
{% if user.profile.landline is defined %}
<dd>{{ user.profile.landline }}</dd>
{% endif %}
<dt>Website:</dt>
{% if user.profile.website is defined %}
<dd>{{ user.profile.website }}</dd>
{% endif %}
有没有办法避免这样做?在显示之前检查变量是否已定义的更好更短的方法?
【问题讨论】: