Twig Extender

Component ID

2682699

Component name

Twig Extender

Component type

module

Maintenance status

Development status

Component security advisory coverage

covered

Downloads

7345

Component created

Component changed

Component body

Add a simple plugin system to add new twig extensions (Filter and Functions). Provides a new service provider for "twig.extensions" to add new plugins.

Versions

Drupal 8.2 or lower: Use Twig Extender 8.1
Drupal 8.3 or higher: Use Twig Extender 8.2

Included filters and functions

Filter: truncate

A Wrapper for https://api.drupal.org/api/drupal/core!lib!Drupal!Component!Utility!Unic...

{{"A long text should be truncated":truncate(8)}}

Function: block_view

Show a block from a existing block config.

  {{ block_view('config_entity_id') }}

Function: block_create

Show a block from a existing plugin id.

  {{ block_create('plugin_id', [<plugin-config>]) }}

Show main menu block with from level 2 with depth 1

  {{ block_create('system_menu_block:main', {level: 2, depth: 1}) }}

Function: is_user_logged_in

Check if user is logged in.

{% if user_is_logged_in() %}
Hello user
{% else %}
Please login
{% endif %}

Function: is_front

Check if the current page is the front page.

{% if is_front() %}
On frontpage
{% endif %}

Filter: to_url

{{ node | to_url }}
{{ urlObject | to_url }}

Add new functions and filters

Please add your suggestions here.
https://www.drupal.org/node/2701695

Simple Plugin

<?php

namespace Drupal	wig_extenderPluginTwigPlugin;

use Drupal	wig_extenderPluginTwigTwigPluginBase;
use DrupalComponentUtilityUnicode;

/**
 * Example plugin Hello World.
 *
 * @TwigPlugin(
 *   id = "twig_extender_hello",
 *   label = @Translation("Hello world plugin"),
 *   type = "function",
 *   name = "hello",
 *   function = "hello"
 * )
 */
class HelloWorld extends TwigPluginBase {

  /**
   * Implement hello world function.
   */
  public function hello() {
    return 'Hello World';
  }

}

Using in Template

{% hello() %}

More will follow.

Sponsored by http://www.b-connect.de