检查变量是否为Twig中的字符串或数组

hsz*_*hsz 47 twig

是否可以检查给定变量是否为字符串Twig

预期的解决方案:

messages.en.yml:

hello:
  stranger: Hello stranger !
  known: Hello %name% !
Run Code Online (Sandbox Code Playgroud)

Twig 模板:

{% set title='hello.stranger' %}
{% set title=['hello.known',{'%name%' : 'hsz'}] %}

{% if title is string %}
  {{ title|trans }}
{% else %}
  {{ title[0]|trans(title[1]) }}
{% endif %}
Run Code Online (Sandbox Code Playgroud)

有可能这样做吗?或许你有更好的解决方案?

Dar*_*Bee 119

可以通过测试完成iterable,在twig1.7中添加,正如Wouter J在评论中所述:

{# evaluates to true if the foo variable is iterable #}
{% if users is iterable %}
    {% for user in users %}
        Hello {{ user }}!
    {% endfor %}
{% else %}
    {# users is probably a string #}
    Hello {{ users }}!
{% endif %}
Run Code Online (Sandbox Code Playgroud)

参考:可迭代


hsz*_*hsz 9

好的,我做到了:

{% if title[0] is not defined %}
    {{ title|trans }}
{% else %}
    {{ title[0]|trans(title[1]) }}
{% endif %}
Run Code Online (Sandbox Code Playgroud)

丑,但有效.

  • 如果数组在`[0]`索引处没有任何内容,则无效 (8认同)

Sir*_*sen 8

我发现iterable不够好,因为其他对象也可以迭代,并且明显不同于array.

因此,添加新内容Twig_SimpleTest以检查项目is_array是否更明确.您可以将此添加到您的应用配置/ twig引导后.

$isArray= new Twig_SimpleTest('array', function ($value) {
    return is_array($value);
});
$twig->addTest($isArray);
Run Code Online (Sandbox Code Playgroud)

用法变得非常干净:

{% if value is array %}
    <!-- handle array -->
{% else %}
    <!-- handle non-array -->
{% endif % }
Run Code Online (Sandbox Code Playgroud)

  • 旁注:此测试将为实现 ArrayAcces、Traverseable 等的每个自定义对象返回 false。 (2认同)
  • 您将测试放入 TwigExtension 子类(在 `getTests` 方法中),将其注册为服务,并将标签 `twig.extension` 添加到服务定义中。标签是让 TwigBundle 为你处理 `addExtension` 的原因。更多细节在这里:http://symfony.com/doc/current/templating/twig_extension.html (2认同)