如何在Symfony 4中使用Twig截断(truncate)函数?

4

我想在Twig中使用truncate过滤器,但是出现了错误:

The file "D:\projets\dzairdeals\config/services.yaml" does not contain valid YAML: Indentation problem in "D:\\projets\\dzairdeals\\config/services.yaml" at line 30 (near " twig.extension.text:") in D:\projets\dzairdeals\config/services.yaml (which is loaded in resource "D:\projets\dzairdeals\config/services.yaml").

当我尝试将这些行添加到我的services.yaml文件时:

twig.extension.text:
     class: Twig_Extensions_Extension_Text
     tags: - { name: twig.extension }

你执行过 composer require twig/extensions 命令了吗? - Dylan Delobel
是的,我已经安装了Twig扩展。 - hocine Badi
1
根据错误提示,似乎只是您的 yaml 文件中的格式问题。请检查文件缩进。 - titili
3个回答

14

对于任何想学习Symfony 5的人:

composer require twig/string-extra
composer require twig/extra-bundle

然后您可以像这样使用 truncate 过滤器:

{{ project.title|u.truncate(30, '...') }}

Truncate过滤器接收一个长度以及可选的字符串(如果截断)附加到结尾。

u.左侧的字符串被包含在Unicode对象中,参见https://twig.symfony.com/doc/2.x/filters/u.html


twig/string-extra 是唯一需要的,不过 "u." 是很有趣的东西... - Mecanik
1
@Mecanik,“u.”是将字符串封装在Unicode对象中的方法。https://twig.symfony.com/doc/2.x/filters/u.html - allan.simon

1

请确保已安装twig/extensions
composer require twig/extensions,如果已经安装,则会自动生成一个包含以下内容的配置文件:

"最初的回答"

#config/packages/twig_extensions.yaml

services:
    _defaults:
        public: false
        autowire: true
        autoconfigure: true

    # Uncomment any lines below to activate that Twig extension
    #Twig\Extensions\ArrayExtension: null
    #Twig\Extensions\DateExtension: null
    #Twig\Extensions\IntlExtension: null
    #Twig\Extensions\TextExtension: null

twig/extensions已被弃用,请改用extra-bundle。 - Acyra

0

你的yaml文件的正确缩进应该是:

twig.extension.text:
         class: Twig_Extensions_Extension_Text
         tags:
            - { name: twig.extension }

或者

twig.extension.text:
     class: Twig_Extensions_Extension_Text
     tags: [twig.extension]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接