[Fixed]-Django – Rendering tooltips stored in the database in templates

1πŸ‘

βœ…

The Django documentation explains how to create template tags.

Could be as simple as:

from django import template

register = template.Library()

@register.simple_tag
def tooltip(key):
    try:
        tooltip = Tooltip.objects.get(key=key)
        return tooltip.message
    except Tooltip.DoesNotExist:
        return ''  # or return a message stating that the key does not exist.

You need to save this file in your app’s templatetags/ directory, along with an __init__.py. You can then {% load "<appname>" %} in your template and use the tag like you suggested.

While you might not need a database to store these, if you do, at least add an index to the key field on your model.

πŸ‘€Jieter

Leave a comment