Truncate text in Twig & Symfony 2

In the core symfony / twig do not have a simple truncate-text-function, like substr() in PHP. Therefor you have to activate the Twig-Text-Extension:

Now you can easily truncate as you like:

If you want to preserve whole words, you have to set the 2nd parameter:

With the 3rd parameter you can override the default seperator ‘…':

 

Thanks Scott :)

About 

Hi, I'm a Berlin-based developer and working on webstuff since 2000. My focus lies on PHP, TYPO3 and Symfony. 2009 I became a certified TYPO3-Integrator. I worked on projects for clients like Paypal, Union Investment, Commerzbank or Warsteiner.

Go check out my page http://www.christian-baer.com

Published by

Christian Baer

Hi, I'm a Berlin-based developer and working on webstuff since 2000. My focus lies on PHP, TYPO3 and Symfony. 2009 I became a certified TYPO3-Integrator. I worked on projects for clients like Paypal, Union Investment, Commerzbank or Warsteiner. Go check out my page http://www.christian-baer.com

3 thoughts on “Truncate text in Twig & Symfony 2”

    1. I was trying to truncate that was being saved as HTML (using ckeditor) so looking at your tip this is what worked for me

      {{var.long_description | truncate(200, true, ‘…’) |raw }}

  1. I also want functionality as Shairyar Baig wants. Can you please help.

    {{var.description | truncate(100, true, ‘…’) |raw }}

Leave a Reply to Shairyar Baig Cancel reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">