【问题标题】:JS send html with django tagsJS 发送带有 django 标签的 html
【发布时间】:2019-11-28 06:22:29
【问题描述】:

我在 JS 中创建小部件。我想通过 jquery.html() 方法发送 html。但我也在使用 django trans 标签。

这是我在 html 端创建小部件代码后:

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

这是我在 JS 端的代码

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);

我想在 JS 端创建 django 标签,但结果是:

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

我想在js中创建django标签

【问题讨论】:

  • 您需要 django 模板中的 js,而不是单独的 js 文件
  • 我的解决方案:国际化:在 JavaScript 代码 i18n 中

标签: javascript python jquery django django-templates


【解决方案1】:

我认为最简洁的解决方案是使用 Django 模板上下文在 DOM 中传递 JSON 对象。

那么,一步一步来:

创建您的翻译服务器端:

from django.utils.translation import gettext as _

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

将它们传递给上下文:

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

现在,如果您使用的是 Django > 2.1.X,您可以使用此过滤器 https://docs.djangoproject.com/en/2.2/ref/templates/builtins/#json-script 在模板中呈现您的翻译:

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

现在你可以从你的 JS 访问你的翻译:

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

这是一个非常可扩展的解决方案,适用于您的所有翻译,未来要翻译的单词越来越多……

【讨论】:

    【解决方案2】:

    你要做的是在服务器端翻译字符串,你可以用下面的代码来做:

    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>'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-12
      • 1970-01-01
      • 2019-11-25
      • 2013-05-18
      • 2013-11-11
      • 2013-08-08
      • 2011-09-05
      • 2014-02-01
      相关资源
      最近更新 更多