Passing data to your hookables

One of the most powerful aspects of hooks & hookables is an ability to pass their data down to the children. We can have two sources of the context data:

  • Hook-level defined data

  • Hookable-level defined data

The context data from these two sources are merged and passed with the metadata to the hookable template or component, so we can use them.

Example

index.html.twig
    {% raw %}

So, as we see at line 11 we define the index.form hook. But also, we pass the form with using the with keyword. Thanks to it, we are able to pass multiple data to hookables that will hook into the index.form hook.

with { form } is a short-hand for with { form: form }, so the key for our FormView in the context data bag will be form.

Now let's create a Twig template rendering some field from our form, and let's make it a hookable.

index/some_field.html.twig
 {# we can also write it like #}
 
 {% raw %}

You can access the context data in multiple ways, so you can pick the one you like the most. Available options are:

  • getting it directly from the hookable_metadata object like hookable_metadata.context.<data_key>

  • getting the context data bag via the Twig function like get_hookable_context().<data_key>

Sometimes you might want to override some data that are defined at the hook-level. It is possible by defining the same context data key on the hookable level. If the same context data key is defined at both hook-level and hookable-level the hookable-level one is used.

Last updated