Quantcast
Viewing all articles
Browse latest Browse all 294796

Add a unified way of creating twig filters and functions to core

Drupal Core imho is lacking a clean way of adding a TWIG filter or function to a custom module.

It would be really nice if this could be done with the new found services / annotations system, and fortunally enough Erik Seifert created such a system in a contrib module called Twig Extender

For example adding a |truncate filter could easily become one class doing :

namespace Drupal\twig_extender\Plugin\TwigPlugin;

use Drupal\twig_extender\Plugin\Twig\TwigPluginBase;
use Drupal\Component\Utility\Unicode;

/**
 * Example plugin for truncate
 *
 *
 * @TwigPlugin(
 *   id = "twig_extender_truncate",
 *   label = @Translation("Truncate string"),
 *   type = "filter",
 *   name = "truncate",
 *   function = "truncate"
 * )
 */

class Truncate extends TwigPluginBase {
  public function truncate($string, $max_length,$wordsafe = FALSE, $add_ellipsis = FALSE, $min_wordsafe_length = 1) {
    return Unicode::truncate($string, $max_length, $wordsafe , $add_ellipsis , $min_wordsafe_length);
  }
}

source : http://cgit.drupalcode.org/twig_extender/tree/src

I personally believe adding this to core instead of adding a dependency to contrib for every project that wants to extend TWIG. This could save a lot of modules, including one of my own, in re-inventing the wheel on adding Twig extension to a project. Also having a unified way to adding TWIG filters and functions will help DX a lot.

At this moment 8.1.x is in beta, so i guess it's to late to add it to that version, however the impact could be minimal, so it can be added to point release without any issues. Would be nice to convert the core filters and functions, but it's not trivial for a release (IMHO!)

I did not create a patch, because I wanted to check with core devs first if this idea is feasible.


Viewing all articles
Browse latest Browse all 294796

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>