Twig extension providing 'pattern()' function to better load components
This package provides a
pattern() Twig function, useful when used in conjunction with PatternLab.
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)
composer require gambry/pattern-twig-extension
You are ready to use
If you use UI Patterns, you don't need this package.
On other Twig-based application
composer require gambry/pattern-twig-extension or autoload the Twig extension as documented by your
framework or application.
pattern() function is a wrapper of the Twig
Use then in the same way.
It accepts two parameters:
- template [string]: the template to include. This can be any path supported by your Twig loaders. For example PatternLab has its own include rules and helper.
- variables [object]: the variables to pass to the included template.
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
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.