PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, January 21, 2022

[FIXED] Call Twig truncate filter inside a controller

 January 21, 2022     php, symfony, twig     No comments   

Issue

I need to use twig truncate filter inside a controller. I do not use a Twig template because my controller only return a json object.

From the Twig Text extension source, I saw that the filter function is twig_truncate_filter, so I tried to get the extension as a service and call the filter function it in my controller :

$something = "a long character string that need to be truncated";
$twigText = $this->get("twig.extension.text");
$twig = $this->get("twig");
$truncatedValue = $twigText->twig_truncate_filter($twig,$something)

It give me a Fatal error: Call to undefined method Twig_Extensions_Extension_Text::twig_truncate_filter().

How can I use the filter feature directly in my controller ?


Solution

Probably there is a shorter way, but the following worked for me:

$filters = $this->get('twig.extension.text')->getFilters();
$callable = $filters['truncate']->getCallable();

$truncated = $callable($this->get('twig'), $str));

For Twig Extensions > 1.3 you can use this

$filters = $this->get('twig.extension.text')->getFilters();
$key = array_search('truncate', array_map(function(TwigFilter $filter) { return $filter->getName(); }, $filters), true);
$callable = $filters[$key]->getCallable();
    
$truncated = $callable($this->get('twig'), $str));


Answered By - VisioN
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing