hocine Badi
hocine Badi

Reputation: 51

How can i use twig truncate in Symfony 4

I want to use trancate filter in twig but i have the error:

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").

When I try to add this lines to my services.yaml

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

Upvotes: 5

Views: 8007

Answers (3)

Sherri
Sherri

Reputation: 943

For anyone coming to this for Symfony 5:

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

Then you can use the truncate filter like so:

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

Truncate filter is passed a length and an optional string to append to the end if truncated.

u. meaning the string on the left is encapsulated in a Unicode object, see https://twig.symfony.com/doc/2.x/filters/u.html

Upvotes: 17

Arnaud Anato
Arnaud Anato

Reputation: 99

Make sure twig/extensions is installed:
composer require twig/extensions, if so, you should see a config file auto-generated containing:

#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

Upvotes: 1

titili
titili

Reputation: 207

A correct indentation for your yaml file could be :

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

or

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

Upvotes: 0

Related Questions