What's on this page
Add a custom Twig function or filter
Cecil provides many template functions and filters, but you can add your own with a Twig extension written in PHP.
Create the extension class
Add a PHP file in the extensions directory of your site, with your own namespace (e.g.: MySite\Twig, the Cecil\ namespace being reserved), the file path matching the namespace:
extensions/MySite/Twig/MyTwigExtension.php
<?php
namespace MySite\Twig;
class MyTwigExtension extends \Twig\Extension\AbstractExtension
{
public function getFilters(): array
{
return [
// {{ 'text'|md5 }}
new \Twig\TwigFilter('md5', 'md5'),
// {{ page.content|word_count }}
new \Twig\TwigFilter('word_count', [$this, 'wordCount']),
];
}
public function getFunctions(): array
{
return [
// {{ year() }}
new \Twig\TwigFunction('year', fn () => date('Y')),
];
}
public function wordCount(string $html): int
{
return str_word_count(strip_tags($html));
}
}
Register the extension
Add the class name to the layouts.extensions map in cecil.yml, indexed by a name of your choice:
layouts:
extensions:
MyExtension: MySite\Twig\MyTwigExtension
Use it in templates
<p>{{ page.content|word_count }} words</p>
<footer>© {{ year() }} {{ site.title }}</footer>