• 4
name

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 191

Backtrace:

File: /home/prodcxja/public_html/questions/application/views/question.php
Line: 191
Function: _error_handler

File: /home/prodcxja/public_html/questions/application/controllers/Questions.php
Line: 433
Function: view

File: /home/prodcxja/public_html/questions/index.php
Line: 315
Function: require_once

name Punditsdkoslkdosdkoskdo

Call Twig truncate filter inside a controller

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 ?

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 = $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));
  • 10
Reply Report

If you look closely at the Twig/Extensions/Extension/Text file, you'll see that twig_truncate_filter is actually declared as a global function, not part of the Twig_Extensions_Extension_Text class.

That class merely acts as a wrapper for a Twig filter, truncate, to call that global twig_truncate_filter function.

You can simply call it directly in your controller:

$truncatedValue = twig_truncate_filter($twig, $something);
  • 6
Reply Report
      • 1
    • @duncan This is true with Twig's Intl filters which I am glad to say has promptly ended a couple of hours of unsuccessful attempts to localise dropdown text with a date in it. Thanks for the insight!

Warm tip !!!

This article is reproduced from Stack Exchange / Stack Overflow, please click

Trending Tags

Related Questions