2

I am cretaing widget in JS. And I want to send html through jquery.html() method. But I am using also django trans tag.

This is my after cretating widget code on html side:

<div class="modal-header" style="padding: 5px;padding-left: 25px;">
    <h5 class="modal-title" id="componentName">{% trans "Report" %}</h5>
</div>

And this is my code on JS side

html = '<div class="modal-header" style="padding: 5px;padding-left: 25px;">'+
      '<h5 class="modal-title" id="'+IdCreateHelper(component_names[i])+'">'+'{% trans "'+component_names[i]+'" %}'+'</h5>'+
'</div>'

$('#'+modal_id).html(html);

I want to create django tags on JS side but result is:

{% trans "Reports" %}
<h5 class="modal-title" id="componentName">{% trans "Report" %}</h5>

I want to create django tags in js

2
  • You'll need the js within the django template rather than as a separate js file Commented Jul 19, 2019 at 10:38
  • My solution : Internationalization: in JavaScript code i18n Commented Aug 22, 2019 at 8:51

2 Answers 2

2

I think that the cleanest solution is pass a JSON object in your DOM using the Django template context.

So, step by step:

Create your translations server side:

from django.utils.translation import gettext as _

translations = {
    'report': _('Report')
}

Pass them to the context:

return render(request, 'mytemplate.html', context={'translations': translations})

Now, if you are using Django > 2.1.X you can render your translations in the template using this filter https://docs.djangoproject.com/en/2.2/ref/templates/builtins/#json-script:

{{ translations|json_script:"my-translations" }}

Now you can access your translations everywhere from your JS:

var translations = JSON.parse(document.getElementById('my-translations').textContent);
console.log(translations.report)

This is a very scalable solution for all your translations, with future words to translate growing and growing...

Sign up to request clarification or add additional context in comments.

Comments

2

What you have to do is translate the string in server side, you can do it with the following code:

from django.utils.translation import gettext as _

html = '<div class="modal-header" style="padding: 5px;padding-left: 25px;">' + 
'<h5 class="modal-title" id="' + IdCreateHelper(component_names[i]) + '">' + 
_(str(component_names[i])) +'" %}'+'</h5>'+'</div>'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.