47👍
You can use the blocktrans
template tag in this case:
{% blocktrans %} This is the title: {{ myvar }} {% endblocktrans %}
33👍
{% trans myvar %}
just works. So check your PO file to make sure that the value of myvar
is in PO msgid.
<title>{% trans myvar %}</title>
For example if myvar
contains "Some Publisher"
you can write the following in the PO file:
msgid "Some Publisher"
msgstr "কিছু প্রকাশক"
Also make sure you have ran:
python manage.py compilemessages
- [Django]-Feedback on using Google App Engine?
- [Django]-What is the max size of 'max_length' in Django?
- [Django]-When to use Serializer's create() and ModelViewset's perform_create()
13👍
Django can’t guess what is in that variable, so you have to translate it yourself by adding both the english (msgid
) and the localized (msgstr
) strings.
- [Django]-Django get a QuerySet from array of id's in specific order
- [Django]-What is the canonical way to find out if a Django model is saved to db?
- [Django]-How do I display the value of a Django form field in a template?
6👍
My experience here is that variable translation does not work in templates on its own. However I came to a suitable solution when the content of the variables is known (I mean that they are not free text, but a set of choices you set in the database).
You need to force the translation in the view or in a filter tag.
To sum up:
- Use
blocktrans
in your templates - Force variables to be translated
- You either set variables in context that are already marked for transtalion
- or use a filter to translate them
- Generate translations in
.po
file
The story is like this:
views.py
def my_view(request):
return render(request, 'i18n_test.html', {'salutation':"Hola"})
templates/i18n_test.html
...
{% blocktrans %}{{ salutation }}{% endblocktrans %}
...
And when I render the template it always shows Hola whichever the current language is.
To force the translation, in the view we need to use ugettext.
def my_view(request):
return render(request, 'i18n_test.html', {'salutation':ugettext("Hola")})
However it is not always possible to access the view. So I prefer to use a filter like this.
templatetags/i18n_extras.py
@register.filter(name='translate')
def translate(text):
try:
return ugettext(text)
And the template becomes
...
{% blocktrans s=salutation|translate %}{{ s }}{% endblocktrans %}
...
And produces Hola, Hello, Ciao, Salut depending on the current language.
The disadvantage (as pointed out in the docs ) is that makemessages
does not automatically include these translations, so we need to include them manually. In django.po file:
locales/en/django.po
...
msgid "Hola"
msgstr "Hello"
...
- [Django]-Django index page best/most common practice
- [Django]-Django Rest Framework with ChoiceField
- [Django]-In Django, how does one filter a QuerySet with dynamic field lookups?
1👍
You can translate the variable in the python code like here for settings.SITE_NAME
:
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
def processor004(request):
my_dict = {
'site_id004': settings.SITE_ID,
'site_name004': _(settings.SITE_NAME),
'installed_apps004': settings.INSTALLED_APPS,
'embedded_widget004': settings.EMBEDDED_WIDGET,
'base_template004': settings.BASE_TEMPLATE,
}
return my_dict
- [Django]-How can one use enums as a choice field in a Django model?
- [Django]-Can't compare naive and aware datetime.now() <= challenge.datetime_end
- [Django]-Django – No such table: main.auth_user__old
1👍
make own tags
from django.utils.translation import ugettext as _
@register.simple_tag
def trans2(tr, *args, **kwargs):
# print(':', kwargs)
trans = _(tr)
trans_str = trans.format(**kwargs)
return trans_str
in template:
{% trans2 columns_once.res_data.message with value=columns_once.res_data.recommend%}
in django.po
#: default_content.py:136
msgid "_audit_recommend_speed"
msgstr "Рекомендованная скорость до {value} сек"
- [Django]-Race conditions in django
- [Django]-Do django db_index migrations run concurrently?
- [Django]-How to properly use the "choices" field option in Django
1👍
As one workaround, you can collect {% trans %}
(django 3.0 and below) or {% translate %}
(django 3.1 and above) tags between {% comment %}
and {% endcomment %}
in one template. This will save your efforts to repeat typing the same msgid should you have more than one language po file.
{% comment %}
{% trans "Tea" %}
{% trans "Clothes" %}
{% endcomment %.}
Make sure you run django-admin makemessages --all
after putting the aforementioned code.
- [Django]-Site matching query does not exist
- [Django]-How to revert the last migration?
- [Django]-Django index page best/most common practice
0👍
It’s a complex elegant solution that may help if you are translating values from model fields: http://django-modeltranslation.readthedocs.org
“Modeltranslation
The modeltranslation application is used to translate dynamic content of existing Django models to an arbitrary number of languages without having to change the original model classes.”
- [Django]-How do I restart celery workers gracefully?
- [Django]-Do CSRF attacks apply to API's?
- [Django]-Passing Python Data to JavaScript via Django
0👍
To me, this happened when I had the TEMPLATES.DIRS
outside my Django project directory. Fetching the templates into the project directory solved the problem.
- [Django]-Django models avoid duplicates
- [Django]-Django 1.4 – can't compare offset-naive and offset-aware datetimes
- [Django]-How do I add a placeholder on a CharField in Django?