Passing data to your hookables

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

  • Hook-level defined data

  • Hookable-level defined data

Context data from these two sources is merged and passed to the hookable template or component together with the metadata , so we can access them.

Example

Let's assume we want to render a form in our index.html.twig template via a form variable containing a FormView instance.

Here, we define an index.form hook, and we can pass it the form's context data thanks to the with keyword.

This means that we can technically pass down multiple pieces of data to hookables that will hook into index.form.

index.html.twig
<div class="container">
    {{ form_start(form) }}
    {{ form_errors(form }}
    {{ form_widget(form._token) }}
    
    {% hook 'index.form' with { form } %}
    
    {{ form_end(form, {render_rest: false} }}
</div>

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 that renders a field from our form and let's make it a hookable. We have 3 possible options to do this :

index/some_field.html.twig
<div class="field">
  {{ form_row(hookable_metadata.context.form.some_field) }}
 </div>

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>

Override behavior

When the same context data key is defined at both the hook and hookable levels, the hookable-level value takes precedence.

You can use this to override hook-level data by redefining the key at the hookable level.

Last updated