gambry/pattern-twig-extension

Twig extension providing 'pattern()' function to better load components

Installs: 230

Dependents: 0

Suggesters: 0

Security: 0

Stars: 3

Forks: 0

Type:patternlab-twig-extension

0.0.7 2019-02-25 10:59 UTC

This package is auto-updated.

Last update: 2024-04-15 14:36:11 UTC


README

This package provides a pattern() Twig function, useful when used in conjunction with PatternLab.

Use cases

You need this package if either:

  • You use PatternLab with Twig (yeah, why not? :D )
  • PatternLab components are consumed by Drupal through UI Patterns (or UI Patterns PatternLab)
  • You {% include %} patterns in patterns, but this solution is too limited for your use case, i.e. you need to run custom logic on inclusion like loading component CSS or Javascript.

Installation

On PatternLab

Simply run: composer require gambry/pattern-twig-extension

You are ready to use pattern().

On Drupal

If you use UI Patterns, you don't need this package.

On other Twig-based application

Either run composer require gambry/pattern-twig-extension or autoload the Twig extension as documented by your framework or application.

Basic Usage

The pattern() function is a wrapper of the Twig include function. Use then in the same way.

It accepts two parameters:

If you consume your PatternLab patterns on Drupal through UI Patterns, you should use the pattern name as template parameter, without the .twig extension. For example if you need to include the button component - stored in 00-atoms/button/button.twig for full compatibility you should use pattern('button').

Advanced Usage

This library makes use of the Symfony EventDispatcher component in order to allow developer to react and add their own logic.

When calling a pattern through pattern() two event are dispatched:

  • PatternTwig\Pattern\Event\IncludeEvent::PRE_INCLUDE: triggered before the inclusion starts. Developers can subscribe to this event when they want to alter or react during the template loading process. For example if the template or its variables need to be changed.
  • PatternTwig\Pattern\Event\IncludeEvent::POST_INCLUDE: the template has been loaded and its output rendered. Developers can subscribe to this event for example for altering the template output. Also if CSS/JS libraries must be loaded this is now a good moment as we know Twig has found and rendered the template.

For both events a PatternTwig\Pattern\Event\IncludeEvent is provided, which has method to override the template, the variables and the output.