JS组件开发:如何在jQuery.html()中正确使用Django trans标签
Django's {% trans %} tag is processed server-side when the template is rendered. By the time your JavaScript runs in the browser, Django has already finished processing the page—so the {% trans %} string you're building in JS gets inserted into the DOM as literal text, not translated content. That's why you're seeing unexpected results.
Here are a few solid solutions to fix this:
Solution 1: Pre-Translate Component Names in the Template
The simplest approach is to let Django handle all translations upfront, then pass the translated strings to your JavaScript.
Step 1: Create a Translation Map in Your Django Template
Add this script block somewhere in your template (before your component JS runs):
{% load i18n %} <script> // Create a map of original component names to their translated versions const componentTranslations = { {% for name in component_names %} "{{ name|escapejs }}": "{% trans name %}", {% endfor %} }; </script>
escapejsensures any special characters in component names are safely escaped for JavaScript.- Django processes the
{% trans %}tags here, so each value is already the translated string.
Step 2: Use the Translation Map in Your JS
Modify your JavaScript to pull the pre-translated string instead of trying to use {% trans %}:
const translatedName = componentTranslations[component_names[i]] || component_names[i]; // Fallback to original if no translation exists const html = `<div class="modal-header" style="padding: 5px;padding-left: 25px;"> <h5 class="modal-title" id="${IdCreateHelper(component_names[i])}">${translatedName}</h5> </div>`; $('#' + modal_id).html(html);
Solution 2: Use Django's JavaScript Catalog
If you need to translate dynamic strings that aren't known upfront, use Django's built-in JavaScript internationalization support.
Step 1: Set Up the JavaScript Catalog
Add this to your project's urls.py:
from django.views.i18n import JavaScriptCatalog urlpatterns = [ # ... other urls path('jsi18n/', JavaScriptCatalog.as_view(), name='javascript-catalog'), ]
Step 2: Include the Catalog in Your Template
Add this script tag to your template:
{% load i18n %} <script src="{% url 'javascript-catalog' %}"></script>
Step 3: Translate Strings Directly in JS
Now you can use the gettext function (just like in Django templates) in your JavaScript:
const translatedName = gettext(component_names[i]); const html = `<div class="modal-header" style="padding: 5px;padding-left: 25px;"> <h5 class="modal-title" id="${IdCreateHelper(component_names[i])}">${translatedName}</h5> </div>`; $('#' + modal_id).html(html);
- This works for any string that's been marked for translation in your Django project (make sure
component_names[i]is included in your translation files).
Solution 3: Fetch Rendered HTML via AJAX (For Complex Cases)
If your component's HTML is more complex and you want Django to render the entire snippet server-side, create a view that returns the rendered template, then fetch it with AJAX:
Step 1: Create a Django View
from django.shortcuts import render def component_modal_header(request, component_name): return render(request, 'modal_header.html', {'component_name': component_name})
Step 2: Create the Template Snippet (modal_header.html)
{% load i18n %} <div class="modal-header" style="padding: 5px;padding-left: 25px;"> <h5 class="modal-title" id="{{ component_name|slugify }}">{% trans component_name %}</h5> </div>
Step 3: Fetch and Insert the HTML in JS
$.ajax({ url: `/path/to/your/view/${component_names[i]}`, success: function(html) { $('#' + modal_id).html(html); } });
- This adds an extra HTTP request, but it's useful if you have complex template logic beyond just translations.
All three solutions will correctly handle translations—pick the one that best fits your use case!
内容的提问来源于stack exchange,提问作者mete eroğlu

