【问题标题】:Django templates: include template passing translated variableDjango模板:包括模板传递翻译变量
【发布时间】:2023-03-09 10:45:01
【问题描述】:

我需要通过 Django include 标签将以下内容传递到包含的模板中:

{% include 'btn.html' with
     btn_text='Hi '|add:first_name|add:' - Verify Email Now'
     btn_url=verify_url
%}

因此,我可以将整个问题分为两部分:

A. 是否可以在模板级别以另一种更优雅的方式将first_name 添加到字符串中

B. 我需要在模板级别翻译字符串 - 可以吗?

即我打算做的(但在语法上是正确的)如下:

{% include 'btn.html' with
     btn_text=
         {% blocktrans first_name as first_name %}
             Hi {{first_name}} - Verify Email Now
         {% endblocktrans %}
     btn_url=verify_url
%}

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    我在post找到了解决方案:

    这是给定的示例:

    {% trans "Load more promotions" as promotions %}
    {% include "a_dir/stuff.html" with text=promotions %}
    

    【讨论】:

      【解决方案2】:

      要格式化字符串,您可以在视图中执行此操作并将其传递到上下文中:

      context = {'btn_text': 'Hi {0} - Verify Email Now'.format(first_name)}
      return HttpResponse(context=context)
      

      有关文本的翻译,请查看以下链接:
      https://docs.djangoproject.com/en/1.2/topics/i18n/internationalization/#trans-template-tag

      【讨论】:

      • 需要完全在模板级别完成。不过,还是感谢您的建议。
      • 如果真的想在模板级别这样做,那么我建议你创建一个custom template tag,因为 django 不提供任何模板标签来格式化字符串。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-01
      • 1970-01-01
      • 2017-03-10
      • 1970-01-01
      • 2019-04-03
      • 2021-02-15
      • 2010-10-25
      相关资源
      最近更新 更多