2

I have a twig template in which i render some information taking from the database. The length of the information is quite large and it does not fit in the space provided for it. I want to use substr function of php inside my twig template.

The index.html.twig contains

 <span>{{ patent.description }}</span>

The description is very long I want to display the first 80 characters of the whole description.

In php I can use

 substr(patent.description,0,80)

Can anyone guide me how i can use this function inside my twig template?

2
  • you can do it before passing it to the template. maybe in your controller Commented Oct 3, 2012 at 22:53
  • I have multiple entries and for each entry i take its name and description. from controller I pass just patents and then in my template i use foreach patent Commented Oct 3, 2012 at 22:55

1 Answer 1

6

The slice function does this,

<span>{{ patent.description|slice(0,80) }}</span>

The slice filter works as the array_slice PHP function for arrays and substr for strings. It was added in Twig 1.6.

Sign up to request clarification or add additional context in comments.

1 Comment

After that you can add ... And of course some if statement for case when description is empty. Did the same work today =)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.