drupal 8 twig filters

Solutions on MaxInterview for drupal 8 twig filters by the best coders in the world

showing results for - "drupal 8 twig filters"
Giada
29 Aug 2017
1//Create file: ctwigfilters.services.yml
2services:
3  ctwigfilters.twig_extension:
4    arguments: ['@renderer']
5    class: Drupal\ctwigfilters\TwigExtension\MyHumanize
6    tags:
7      - { name: twig.extension }
8
9//file: ctwigfilters/src/TwigExtension
10<?php
11/**
12 * Created by PhpStorm.
13 * User: Zhilevan
14 * Date: 1/9/18
15 * Time: 23:38
16 */
17namespace Drupal\ctwigfilters\TwigExtention;
18class MyHumanize extends \Twig_Extension {
19    public function getFilters()
20    {
21        return [ new \Twig_SimpleFilter('myhumanize', array($this, 'myHumanize'))];
22    }
23    public function getName()
24    {
25        return 'ctwigfilters.twig_extension';
26    }
27    public static function myHumanize($string)
28    {
29        $str = trim(strtolower($str));
30        $str = preg_replace('/[^a-z0-9\s+]/', '', $str);
31        $str = preg_replace('/\s+/', ' ', $str);
32        $str = explode(' ', $str);
33        $str = array_map('ucwords', $str);
34        return implode(' ', $str);
35    }
36}
37
38// in twig file
39{{ your-variable | myhumanize }}