TWIG:变量在一个长列表中定义

TWIG: variable is defined in a long list

我正在用 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 %} 

有没有办法避免这样做?在显示之前检查变量是否定义的更好和更短的方法?

直接回答你的问题:不,据我所知没有捷径,除了使用三元运算符:

{{ user.profile.landline is defined ? user.profile.landline : "" }}

甚至更短的语法

{{ user.profile.landline is defined ? user.profile.landline }}

但我想说这些检查应该在控制器中进行,这样 Twig 中的变量总是被定义的。 Twig 模板中的条件越少越好。

不知道这是否符合您的需求,但您可以这样做:

<dd>{{ user.profile.landline|default("") }}</dd>

至于过滤后的数据,做法类似:

<dd>{{ user.firstname|default("")|title }}</dd>

现在,问题是日期。我假设,您不想将其默认为 today 或任何其他与此相关的内容。

@Francesco 也发布了非常简单的解决方案,所以它可能会更好,具体取决于您真正想要实现的目标(例如,仅当数据是定义、日期属性等...)。

希望对您有所帮助

您还可以更改 twig 的配置:

If a variable or attribute does not exist, you will receive a null value when the strict_variables option is set to false; alternatively, if strict_variables is set, Twig will throw an error (see environment options). Source

在 config.yml 的正确部分添加以下行:

twig:
     strict_variables: false

Here 你得到了更多信息。

编辑: 正如@Jovan Perovic 在评论部分中已经提到的那样,这个解决方案有点 冒险 。设置 strict_variables: false Twig 不会抛出任何关于您使用的变量的异常,即使您在变量名称中输入了一个简单的错字。这会使您的代码验证变得更加复杂。