Search code examples
djangodjango-templatesdjango-i18n

Apply filter to result of Django custom template tag (like i18n trans)


We have a Django project with a legacy translation module that stores translations in the database, and does not use Django i18n (gettext).

We have written custom template tags {% db_trans ... %} that work like Django's default {% trans ... %}, but there is one trick we cannot duplicate.

In this example, "tree" (English) translates to "boom" (Dutch).

In my Django template, if I use default i18n and write {% trans "tree" %} I will see the result boom. When I want to use this as a title, I use the capfirst filter like this {% trans "tree"|capfirst %}, and the result will be Boom. Note the capital B.

This seems to be a special trick. Our db_trans custom tag (based on simple_tag) capitalizes the input before translation. Since there is no translation in the database for Tree, {% db_trans "tree"|capfirst %} renders its default (untranslated) value, Tree.

  • I now about {% filter capfirst %}...{% endfilter %} and will probably use it if we cannot find an easy solution.
  • I have checked the Django source code and I saw that {% trans ... %} is not based on simple_tag and does quite a lot of text argument parsing.

My question: is there a package or snippet that allows a filter specified as shown above to be applied to the result of a custom tag?


Solution

  • If you make your template tag a filter, then you can chain it with capfirst built-in filter

    from django import template
    
    register = template.Library()
    
    @register.filter
    def db_trans(word, request):
        return do_the_translation(word, request)
    

    Then in the html it would look like this

    {{ 'tree'|db_trans:request|capfirst }}