How to create a Tooltip in Twig

Last updated on
7 April 2022

This page is an example of how to use the Tooltip module in Drupal.

It is possible to create a Tooltip with your Twig template only.

You just need to 1) load the library and 2) add a data-tooltip attribute on a element in your HTML, as follow:

{{ attach_library('tooltip/tooltip') }}

{% set blockId = "mycustomblockID" %}
{% set options = {"block": blockId, "placement": "top"} %}

<div class="tooltip visually-hidden" data-tooltip-id="{{ blockId }}">
  This is the block displayed on hover.
  {# Uncomment next line to display Tooltip's arrow #}
  {# <div data-popper-arrow></div> #}
</div>

<button data-tooltip="{{ options|json_encode }}">Hover me!</button>

Or content directly as follow:

{{ attach_library('tooltip/tooltip') }}

{% set options = {"content": "<div>This is<br>the tooltip content</div>", "placement": "top"} %}

<button data-tooltip="{{ options|json_encode }}">Show me</button>

The data-tooltip attribute expects a JSON-encoded object with the following:

{
  "block": "aCustomBlockID",    // Use a Block by ID or UUID.
  "content": "My tooltip text", // OR use arbitrary markup.
  "placememt": "top-start",     // Set position (top,top-end,right-start,right...etc).
  "modifiers": []               // Set modifiers (cf. https://popper.js.org/docs/v2/modifiers)
}

Help improve this page

Page status: No known problems

You can: