Django's own {% trans%} tag
I wrote a template tag for Django that is used for example by {% foo bar="foobar"%}
. The tag takes the value of an argument bar
, uses ugettext
on it, and displays the tag with the translated string.
So, basically the implementation of the tag looks like this:
@register.simple_tag
def foo(bar):
return "something something " + ugettext(bar)
Unfortunately we are using ugettext
with a variable, which means that Django will not mark our argument value bar
for translation.
I searched for a solution in Django makemessages
as well as code {% trans %}
, but I couldn't find anything that could clearly tell how "marking for translation" is done. So my question is, how do I do this? How do I make Django think my tag value bar
needs to be translated, so it appears in the .po (t) file after execution manage.py makemessages
?
source to share
Instead of creating a "custom" trans tag, you can pass in a string using syntax _()
, so the argument gets the already translated string.
In the case of the tag from the question, this means that we can change the implementation of the tag to a simple one:
@register.simple_tag
def foo(bar):
return "something something " + bar
But you don't need to use something like this:
{% trans "foobar" as var %}
{% foo bar=var %}
And instead:
{% foo bar=_("foobar") %}
It is quite convenient, does not wrap lines and variables, and does not place a line for translation.
source to share