Twig Extensions

What are they?

Extending Twig

"Twig can be extended in many ways; you can add extra tags, filters, tests, operators, global variables, and functions. You can even extend the parser itself with node visitors."

{{ post.published_at|date("m/d/Y") }}

Existing extensions

  • Text: Provides useful filters for text manipulation;
  • I18n: Adds internationalization support via the gettext library;
  • Intl: Adds a filter for localization of DateTime objects, numbers and currency;
  • Array: Provides useful filters for array manipulation;
  • Date: Adds a filter for rendering the difference between dates.

Cool bro, what now?

Add your own!

My example

There are a lot of places in Drupal that accept Twig extensions. One that I have used the most is inside of views.

 

If you see "You may use Twig syntax in this field." Or something along those lines, you can create your own!

Blocks with variable title

This page required that the currently viewed microsite's label is being shown.

 

I am expecting future microsites to have the same sort of page that will need to show it's label as well.

Can't you get this from views?

Short answer, sure.

Let's see how I did it.

Twig Extensions

By Evan Jenkins

Twig Extensions

  • 463