Showing posts with label Twig. Show all posts
Showing posts with label Twig. Show all posts

Monday, April 8, 2019

Create custom Twig function Extentions in Drupal 8

Some times we need custom function that will help us to use custom function to use in Twig file. We can extend the core Twig_Extension to use in our custom module.
Please follow the below steps/code to create custom twig function.
Creating your own Twig Extension function
To start with it first, we need to create a module.
1.) Create a new module inside: /modules/custom/ directory inside your drupal project.
2.) Our new module structure would look like this:
modules
--custom
----demo_module
------demo_module.info.yml
------demo_module.services.yml
------src
--------TwigExtension.php
3.) demo_module.info.yml contains
name: demo_module
type: module
description: 'Provides Twig Extension that process the Regular Expression functions.'
core: 8.x
version: 0.1.1
Information provided inside module_name.info.yml is used to be displayed on admin module page.
4.) Create a service file inside your module as 'module_name.services.yml'
services:
  demo_module.twig.TwigExtension:
    class: Drupal\demo_module\TwigExtension
    tags:
      - {name: twig.extension}
5.) The TwigExtension.php contains the following code
<?php
namespace Drupal\demo_module;
use Drupal\block\Entity\Block;
use Drupal\user\Entity\User;
use Drupal\node\Entity\Node;

/**
* Class DefaultService.
*
* @package Drupal\demo_module
*/
class TwigExtension extends \Twig_Extension {

/**
* {@inheritdoc}
* This function must return the name of the extension. It must be unique.
*/
public function getName() {
return 'pcre_extension';
}
/**
* {@inheritdoc}
*/
public function getFilters()
{
return [
new \Twig_SimpleFilter('pregReplace', [$this, 'pregReplace']),
];
}
/*
* This function is used to return only letters
*/
public function pregReplace($value, $pattern, $replacement = '', $limit = -1) {
if (!isset($value)) {
return null;
}
return preg_replace($pattern, $replacement, $value, $limit);
}
6.) Now, enable your demo_module module.
drush en demo_module -y
7.) Clear the cache.
drush cr
8.) Applying Twig Extension to your twig template
You can make a call to your TwigExtension directly inside template using “{{ }}” braces. These braces are used to render any content placed inside them.

{{ val|pregReplace('/[^A-Za-z]/') }}
Moving further, set the value from pregReplace('/[^A-Za-z]/') function to remove all special characters in Twig template files, it will return only letters.
TwigExtension provides a great accessibility to the code which is often reused. With easy re-usability of the code, it also saves a lot of time and efforts. Hope you will now be able to use Twig in Drupal 8.