So what is TWIG?
Twig is a template engine which is based from PHP. So instead of using PHP native code within our HTML, we use Twig extensions/functions.
In this way, code becomes minimal, making it also faster and lighter to run. Twig is also very flexible, meaning we can create our own Twig tags/functions/extensions!
On this article we will be explaining how to create your own custom Twig function/extension by creating your own module in Drupal. But before you can do this, make sure you know the basics on how to create custom modules, if not you can go to this link to learn more here.
Here are the steps:
1. First is to create your own custom module, by creating a folder with the name of your module under the root/modules/custom/{module_name} directory
2. Second step is to create a service. Pro tip, make sure you have added a tag on your service with the value of "twig.extension" in order for it to be recognized that it is customization of the twig service.
Example:
services:
custom_twig.twig.CustomTwig:
class: Drupal\custom_twig\CustomTwig
tags:
- { name: twig.extension }
3. Create the class you have mentioned in your service. In this example its (Drupal\custom_twig\CustomTwig) class.
Example:
<?php
namespace Drupal\custom_twig;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
use Twig\TwigFunction;
/**
* Custom twig functions.
*/
class CustomTwig extends AbstractExtension {
}
Make sure you have imported the following classes:
A.Twig\Extension\AbstractExtension
B.Twig\TwigFilter
C.Twig\TwigFunction
4. Create a getFilter method within the class you have created. This is in order to tell Twig that we will be creating a custom filter.
Example:
public function getFilters() {
return [
new TwigFilter('reverse_text', [$this, 'ReverstText']),
];
}
5. Now create your method which will have the logic of your filter.
public function ReverstText($text) {
$text = strrev($text);
return $text;
}
6. Finally you can apply your custom filter on twig.
{{ 'Racecar'|reverse_text }}
Don't forget to enable your module and clear cache though!
Next we will be creating a custom function for twig. You may follow the steps 1 - 3 from the procedure above. And follow through with these steps:
4. Create a getFunction method within the class you have created. This is in order to tell Twig that we will be creating a custom filter.
Example:
public function getFilters() {
return [
new TwigFunction('get_nid', [$this, 'getNid']),
];
}
5. Now create your method which will have the logic of your function.
public function getNid($node) {
if (!($node instanceof \Drupal\node\Entity\Node)) {
return;
}
$id = $node->Id();
return $id();
}
6. Finally you can apply your custom function on twig.
{{ get_nid(node) }}
Now that you know how to create custom function and filters in twig, you can take advantage on this technology to make your code more minimal, compact, and optimized.