Skip to content

Commit 03d8c2c

Browse files
atlzakenjis
authored andcommitted
Adding support for filters
1 parent ca00400 commit 03d8c2c

File tree

2 files changed

+33
-2
lines changed

2 files changed

+33
-2
lines changed

README.md

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -82,14 +82,15 @@ $twig = $this->twig->getTwig();
8282

8383
Some helpers are added the functionality of auto-escaping for security.
8484

85-
### Adding Your Functions
85+
### Adding Your Functions & filters
8686

87-
You can add your functions with configuration:
87+
You can add your functions and filters with configuration:
8888

8989
~~~php
9090
$config = [
9191
'functions' => ['my_helper'],
9292
'functions_safe' => ['my_safe_helper'],
93+
'filters' => ['my_filter'],
9394
];
9495
$this->twig = new \Kenjis\CI4Twig\Twig($config);
9596
~~~

src/CI4Twig/Twig.php

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,11 @@ class Twig
4040
'site_url',
4141
];
4242

43+
/**
44+
* @var array Filters to add to Twig
45+
*/
46+
private $filters = [];
47+
4348
/**
4449
* @var array Functions with `is_safe` option
4550
*
@@ -87,6 +92,14 @@ public function __construct($params = [])
8792
unset($params['functions_safe']);
8893
}
8994

95+
if (isset($params['filters'])) {
96+
$this->filters =
97+
array_unique(
98+
array_merge($this->filters, $params['filters'])
99+
);
100+
unset($params['filters']);
101+
}
102+
90103
if (isset($params['paths'])) {
91104
$this->paths = $params['paths'];
92105
unset($params['paths']);
@@ -179,12 +192,29 @@ public function render($view, $params = []): string
179192
// We call addFunctions() here, because we must call addFunctions()
180193
// after loading CodeIgniter functions in a controller.
181194
$this->addFunctions();
195+
$this->addFilters();
182196

183197
$view = $view . '.twig';
184198

185199
return $this->twig->render($view, $params);
186200
}
187201

202+
protected function addFilters()
203+
{
204+
if( !empty($this->filters) ){
205+
foreach ($this->filters as $filter) {
206+
if (function_exists($filter)) {
207+
$this->twig->addFilter(
208+
new \Twig\TwigFilter(
209+
$filter,
210+
$filter
211+
)
212+
);
213+
}
214+
}
215+
}
216+
}
217+
188218
protected function addFunctions()
189219
{
190220
// Runs only once

0 commit comments

Comments
 (0)