【问题标题】:What is the better way of printing and concatinating translated variables in twig?在树枝中打印和连接翻译变量的更好方法是什么?
【发布时间】:2018-10-16 14:52:26
【问题描述】:

假设我有一个类似的设置,翻译后的字符串、变量和分隔符(空格)混合在一个打印中。

{{ "app.user.welcometxt"|trans ~" "~ app.user.name ~" "~ app.user.lastname }}

这是一个好习惯吗? 还是应该将变量放在单独的语句中并一个接一个地打印?

{{ "app.user.welcometext"|trans }} {{ app.user.name }} {{ app.user.lastname }}

解决此问题的最佳方法是什么? 什么是最快或最好的性能?

【问题讨论】:

    标签: html twig string-concatenation


    【解决方案1】:

    虽然我个人认为显式形式更具可读性,但不同代码样式的可读性是一个非常固执的事情。

    显式形式的性能...

    {{ "app.user.welcometext"|trans }} {{ app.user.name }} {{ app.user.lastname }}
    

    ... 肯定更好,因为 Twig 在替换之前不必连接 3 个字符串。我强烈建议您让 Twig 在内部处理这种类型的“优化”。

    使用 Twig 输出用户问候语的更灵活方式如下:

    {% trans with {'%name%': user.name, '%lastname%': user.lastname} from 'app' %}
      {{- app.user.welcometext -}}
    {% endtrans %}
    

    然后将欢迎文本设置为 Hello %name% %lastname% 之类的内容。

    这将允许您轻松附加更多文本(即使用像 Hello %name% %lastname%. How are you feeling today? 这样的问候语)无需更改您的模板。

    【讨论】:

      猜你喜欢
      • 2016-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-23
      • 1970-01-01
      • 2012-02-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多