简体   繁体   English

检查树枝中的YAML字段是否为空

[英]Check if YAML field is empty in twig

I have two .yml files, in each one of them is a translation of my website. 我有两个.yml文件,每个文件都是我网站的翻译。 I reference the fields of the .yml files using twig. 我使用细枝引用.yml文件的字段。 In one translation I need a field that in the other I don't. 在一种翻译中,我需要一个字段,而在其他翻译中,我不需要。 So in one translation I have to reference an empty field. 因此,在一次翻译中,我必须引用一个空字段。 But on the website there is not shown nothing but the "path" of the field. 但是在网站上,除了该字段的“路径”之外,什么都没有显示。 So I want to check if the field is not empty, how is it done? 所以我想检查该字段是否为空,如何完成?

YAML: YAML:

title
    1: string
    2: ~

HTML/Twig: HTML / Twig:

<h4> {{ 'title.1'|trans }}<sup>7</sup>
{% if 'title.2' is not empty %}
     {{ 'title.2'|trans }}
{% endif %}
</h4>

Website: String title.2 网站:字符串title.2

With if 'title.2' is not empty you test a concrete string to be empty, which will never be false . if 'title.2' is not empty ,则测试一个具体的字符串为空,该字符串永远不会为false Even if '' != 'title.2'|trans might not work as it could fall back to a default language. 即使if '' != 'title.2'|trans可能也不起作用,因为它可能会退回到默认语言。


If you explicitly don't want to show a certain text based on the user's locale then test for that. 如果您明确不想基于用户的语言环境显示某些文本,请进行测试。 It also makes your code easier to read and to maintain: 它还使您的代码更易于阅读和维护:

{% if 'en' != app.request.locale %}
    {{ 'title.2'|trans }}                    
{% endif %}

Even shorter: 甚至更短:

{{ 'en' != app.request.locale ? 'title.2'|trans }}

I would also suggest using short words or phrases to identify translations instead of numbers. 我还建议使用短词或短语来标识翻译,而不是数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM