On this page
Quickstart
Last updated on
7 April 2022
This page is an introduction about the Tooltip module in Drupal. It gives an example of a quick implementation to create a Tooltip and to display it programmatically on frontend.
Load the Tooltip library
Attach the library with one of the following options:
1) Programmatically with PHP in a module or a theme with a hook_page_attachments()
// Option 1) Attach the library on every page.
function mymoduleormytheme_page_attachments(&$page) {
$page['#attached']['library'][] = 'tooltip/tooltip';
}2) In your theme.info.yml libraries list
# Option 2: Add the library in your theme.
name: My theme
type: theme
# ...etc
libraries:
- mytheme/global-styling
- tooltip/tooltip3) On demand in your Twig templates
{# Option 3: Attach the library on-demande in Twig #}
{{ attach_library('tooltip/tooltip') }}Create and display a tooltip
In Twig:
{# Now, create your tooltip! #}
{% set options = {"content": "<div>Save the trees 🌲</div>", "placement": "top"} %}
<div data-tooltip="{{ options|json_encode }}">{{ 'Hover me to read more'|t }}</div>
In PHP with the Render API:
$content = '<div>Save the trees 🌲</div>';
$form['tooltip'] = [
'#type' => 'inline_template',
'#template' => '<div data-tooltip="{{ options }}">{{ text }}</div>',
'#context' => [
'text' => t('Hover me to read more!'),
'options' => \Drupal\Component\Serialization\Json::encode([
'content' => \Drupal::service('renderer')->renderPlain($content),
'placement' => 'top',
]),
],
];Help improve this page
Page status: No known problems
You can:
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion