1616use Twig \Error \SyntaxError ;
1717use Twig \Extension \DebugExtension ;
1818use Twig \Loader \FilesystemLoader ;
19+ use Twig \TwigFilter ;
1920use Twig \TwigFunction ;
2021
2122class Twig
@@ -40,6 +41,11 @@ class Twig
4041 'site_url ' ,
4142 ];
4243
44+ /**
45+ * @var array Filters to add to Twig
46+ */
47+ private array $ filters = [];
48+
4349 /**
4450 * @var array Functions with `is_safe` option
4551 *
@@ -61,6 +67,11 @@ class Twig
6167 */
6268 private bool $ functions_added = false ;
6369
70+ /**
71+ * @var bool Whether filters are added or not
72+ */
73+ private bool $ filters_added = false ;
74+
6475 private ?Environment $ twig = null ;
6576
6677 /**
@@ -87,6 +98,13 @@ public function __construct($params = [])
8798 unset($ params ['functions_safe ' ]);
8899 }
89100
101+ if (isset ($ params ['filters ' ])) {
102+ $ this ->filters = array_unique (
103+ array_merge ($ this ->filters , $ params ['filters ' ])
104+ );
105+ unset($ params ['filters ' ]);
106+ }
107+
90108 if (isset ($ params ['paths ' ])) {
91109 $ this ->paths = $ params ['paths ' ];
92110 unset($ params ['paths ' ]);
@@ -176,15 +194,35 @@ public function display($view, $params = [])
176194 public function render ($ view , $ params = []): string
177195 {
178196 $ this ->createTwig ();
197+
179198 // We call addFunctions() here, because we must call addFunctions()
180199 // after loading CodeIgniter functions in a controller.
181200 $ this ->addFunctions ();
201+ $ this ->addFilters ();
182202
183203 $ view = $ view . '.twig ' ;
184204
185205 return $ this ->twig ->render ($ view , $ params );
186206 }
187207
208+ protected function addFilters ()
209+ {
210+ // Runs only once
211+ if ($ this ->filters_added ) {
212+ return ;
213+ }
214+
215+ foreach ($ this ->filters as $ filter ) {
216+ if (function_exists ($ filter )) {
217+ $ this ->twig ->addFilter (
218+ new TwigFilter ($ filter , $ filter )
219+ );
220+ }
221+ }
222+
223+ $ this ->filters_added = true ;
224+ }
225+
188226 protected function addFunctions ()
189227 {
190228 // Runs only once
@@ -196,10 +234,7 @@ protected function addFunctions()
196234 foreach ($ this ->functions_asis as $ function ) {
197235 if (function_exists ($ function )) {
198236 $ this ->twig ->addFunction (
199- new TwigFunction (
200- $ function ,
201- $ function
202- )
237+ new TwigFunction ($ function , $ function )
203238 );
204239 }
205240 }
0 commit comments