get request context in Advanced custom template tags

Viewed 551

In Django simple and inclusion template tags allow getting the request context with

@register.simple_tag(takes_context=True)

Official documentation for custom template tags - inclusion tags.

However, for custom tags, I don't see how this is done.

What I am trying to do is extend the i18n {% trans %} tag, to look for translation in the database first, before using gettext. I need access to the request.Language from the custom template tag.

1 Answers

From the Django doc of custom template tags, it's also possible to add takes_context for customs tags

import datetime
from django import template

register = template.Library()


@register.simple_tag(takes_context=True)
def current_time(context, format_string):

    #use "context" variable here
    return datetime.datetime.now().strftime(format_string)


I'm not sure how to override the existing tag at this particular scenario :(
Anyway, what I'm suggesting is, create a simple_tag that takes the context and do your logic inside the tag and return the translation text from DB. If it's not in DB, return a boolean False. Now in template, check these thing using if tag.

from django import template

register = template.Library()


@register.simple_tag(takes_context=True)
def is_db_available(context):
    # access your context here and do the DB check and return the translation text or 'False'
    if translation_found_in_DB:
        return "Some translation text"
    return False

and in template

{% load custom_tags %}
{% load i18n %}
{% is_db_available as check %} 
{% if check %}  <!-- The if condition  -->
    {{ check }}
{% else %}
    {% trans "This is the title." %} <!-- Calling default trans tag  -->
{% endif %}
Related