I added custom tooltipsJust like this one!
to this website, as I want to provide extra information to specific text in my posts and notes. This can be done using regular shortcodes, which are simple snippets inside a content file that Hugo will render using a HTML
template:
{{< tooltip outer_text="tooltips" tooltip_text="Just like this one!" >}}
This works fine if we just provide simple, static text. One of the criteria for my tooltip shortcode, however, is that I should be able to put other shortcodes inside them, as I have a couple of shortcodes that make use of variables that are updated automatically using GitHub Actions. One example of this is the number of kilometers I ran this year (996.6 km, currently)Updated using GitHub actions + intervals.icu , which I calculate using the intervals.icu API
.
As far as I know, there is no standard way of adding these tooltips in Hugo. I created them myself by using paired shortcodes and using .Inner
to return the content between the opening and closing shortcode tags, which allows us to do the following:
{{< tooltip >}} {{< inner_shortcode >}} {{</ tooltip >}}
Now, we can get the contents of the inner shortcode through .Inner
:
<span class="tooltip"> {{- .Inner | safeHTML -}} <span class="tooltiptext">{{- .Inner | safeHTML -}}</span></span>
We want to put some text as the outer text of the tooltip, and other text in the tooltip box itself, however. Through a hack provided by someone on the Hugo forum, we can split up .Inner
by providing a custom delimiter. For my tooltips, I divide the contents of the paired shortcodes in the outer text and the tooltip text using |
:
{{- $children := split .Inner " | " -}}<span class="tooltip"> {{- index $children 0 | safeHTML -}} <span class="tooltiptext">{{- index $children 1 | safeHTML -}}</span></span>
This way, I can define tooltips like this, for example: 996.6 kmUpdated using GitHub actions + intervals.icu
{{< tooltip >}} {{< distance_run >}} km | See intervals.icu {{</ tooltip >}}