Reputation: 3695
I am using the django {% language %}{% endlanguage %} tag to over-rule the language code of text in my django template with a different language code from a html select list, however it is not working!
Here is my code:
{% language '$("#id_language_code").val()' %}
"{% trans 'to Present' %}"
{% endlanguage %}
The $("#id_language_code").val() is definitely changed when the user selects a value from the html select list. If I append the $("#id_language_code").val() to the translation string above, the changed language code is displayed, but the translation string is not changed. For example:
"{% trans 'to Present' %}" + $('#id_language_code').val()
displays this (where de is the language code selected by the user, but the "to Present" is not translated):
to Present de
If I hard code a language code into the {% language %} tag the translation string is translated. For example:
{% language 'de' %}
Can anyone point out what I am doing wrong?
Upvotes: 3
Views: 368
Reputation: 124804
You seem to be mixing up the server side and the client side.
Django renders the templates at the server side. The browser receives HTML content, which you can manipulate using JavaScript, but Django is out of the picture at that point.
The documentation has a dedicated section about using translations in JavaScript. In a nutshell, Django has a way to expose the dictionaries in the form of a translation catalog that you can use with JavaScript. You will need to change your approach to make it work using this translation catalog instead of the templates alone.
Upvotes: 0
Reputation: 2249
Django templates renders on server - before js is executes on client, so django don`t know what is '$("#id_language_code").val()'.
You need to pass language as variable in template context.
Upvotes: 1