symfony - 使用 for 循环表示 Twig 中的变量

标签 symfony zend-framework2 twig

在我的服务中,我返回一个如下所示的数组:

$array = [
    'bible_anagram_word'    => $result->getBibleAnagramWord(),
    'word_1'                => $result->getWord1(),
    'word_2'                => $result->getWord2(),
    'word_3'                => $result->getWord3(),
    ...
    'word_22'               => $result->getWord22(),
    'word_23'               => $result->getWord23(),
    'word_24'               => $result->getWord24(),
    'word_25'               => $result->getWord25(),
    'Bible_verse_reference' => $result->getBibleVerseReference(),
    'Bible_verse_text'      => $result->getBibleVerseText(),
    'Bible_translation'     => $result->getBibleTranslation(),
];

如何在此 for 循环中表示 document.word_##

{% for i in 1..25 %}
    {{ document.word_ ~ i|slice(0,1) }}
{% endfor %}

在 PHP 中,这段代码是:

substr ( $this->document['word_'.$i] , 0 , 1 )

我不成功的尝试包括:

  • {{ document.word_ ~ i|slice(0,1) }}
  • {{ (document.word_ ~ i)|slice(0,1) }}
  • {{ 'document.word_ ~ i'|slice(0,1) }}

最佳答案

这应该可以解决问题

{{ attribute(document, 'word_' ~ i) }} 

更多关于 attribute function

关于symfony - 使用 for 循环表示 Twig 中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31507881/

相关文章:

zend-framework - ZF 2.4 文件验证器需要 False 不起作用

php - 表单中的 Symfony2 FileType 输入总是返回 null

symfony - fatal error 无法附加到基地址

php - Symfony 更改 'repeated' 字段的样式

php - Symfony - 多对一关系的外部属性的未定义索引

php - 部署 Symfony 应用程序 - ClassNotFoundException 错误

php - Zend框架2 : redirect toRoute shortcircuit not triggering

php - View Helper 中的 Zend Framework 2 服务

Symfony 翻译不起作用

numbers - 在 Twig 模板中格式化金钱