Template Hooks

Craft templates can give modules and plugins an opportunity to hook into them using [hook](../reference/twig/tags.md#hook tags).

{# Give plugins a chance to make changes here #}
{% hook 'my-custom-hook-name' %}

Plugins and modules can register methods to be called by template hooks using craft\web\View::hook() (opens new window).

Craft::$app->getView()->hook('my-custom-hook-name', function(array &$context) {
    // Modify template *context*
    $context['foo'] = 'bar';

    // Return *output*
    return '<p>Hey!</p>';
});

The callback method will pass a $context argument, which represents the current template context (all of the currently defined template variables). Any changes to this array will result in changes to the template’s variables for any tags that follow the {% hook %} tag.

The method can optionally return a string, which will be output where the {% hook %} tag is in the template.

# Control Panel Template Hooks

Your custom plugin or module can use existing template hooks to modify parts of the Craft control panel.

Pay close attention to what you intend to modify; some hooks are provided for modifying context while others make most sense for output.

Hook Description & Template
cp.elements.element Base “element” template, used for rendering relational tiles.
_elements/element.twig (opens new window)
cp.layouts.base Before doctype declaration in base template.
_layouts/base.twig (opens new window)
cp.globals.edit Before global set detail view’s template blocks.
globals/_edit.twig (opens new window)
cp.globals.edit.content After global set detail view’s main content.
globals/_edit.twig (opens new window)
cp.users.edit.prefs After fields in the user’s “Preferences” tab.
users/_edit.twig (opens new window)