Getting started
Twig Hooks are a robust and powerful alternative to the Sonata Block Events and the old Sylius Template Events systems.
Main features
built-in support for Twig templates, Twig Components and Symfony Live Components
adjustability
autoprefixing hooks
configurable hookables
priority mechanism
easy enable/disable mechanism for each hook
Installation
Install the package using Composer and Symfony Flex:
composer require sylius/twig-hooksYour first hook & hookable
Once Twig Hooks is installed, you can open any Twig file and define your first hook.
{% hook 'my_first_hook' %}This way, my_first_hook becomes a unique name which we can use to hook into that specific spot.
Hooking into a hook
For the purpose of this example, let's consider we want to render the some_block.html.twig template inside the my_first_hook hook. First step is to create a twig_hooks.yaml file (or any other format you use) under the config/packages/ directory (if you don't have one already, of course).
Now, we can define our first hookable with the following configuration:
Decomposing the example above we can notice that:
sylius_twig_hooksis the main key for Twig Hooks configurationhooksis a configuration key for defining hookables for all hooksmy_first_hookis our hook name, defined on the Twig file levelsome_blockis the name of our hookable, it can be any string, but it should be unique for a given hook unless you want to override the existing hookable (if you want to read more about overriding hookables check the overriding-hookables.md section)finally we have a
templatekey that defines which template should be rendered inside themy_first_hookhook
Possible hookable configuration options
Depending on the hookable template, we can pass different configuration options while defining hookables:
Conditions in hookables
Unlike the enabled flag — which is evaluated statically during the application boot — the condition option is an Expression Language expression that is evaluated at runtime, each time the hook is rendered. The hookable is rendered only when the expression returns true. Both the whole hook context and the _context variable are available within the expression, so both of these work:
The user variable is provided from Symfony's current security token, as in Symfony security expressions. To refer to a user value passed explicitly in the hook context, use _context.user. For context keys, _context behaves like Twig's defined-style check: @=_context.product returns null when the variable is absent from the context. Referencing a missing variable directly (e.g. @=product ...) throws a clear InvalidExpressionException instead, which makes invalid conditions fail fast during development.
Conditions can also use Symfony's is_granted() authorization check. Pass the required role or attribute, and optionally a subject:
The check uses Symfony's authorization checker, so voters and access decision rules apply as they do in Twig templates.
Last updated
Was this helpful?