【问题标题】:django blocktrans external urldjango blocktrans 外部网址
【发布时间】:2015-06-17 22:00:36
【问题描述】:

我正在使用 django 框架构建一个 Web 应用程序。在我的一个模板中,我想放置一个指向外部 URL 的超链接。

在这个模板中,我需要有两种语言,所以我决定使用 django blocktrans 标签。从the django documentation),我只能把 internal URL 作为 URL。 CMIIW。

如何放置我的外部 URL?

例如。这是英语的template.html。我把http://external/docs/en/作为超链接

{% blocktrans %}
Hello, how are you? <a href="http://external/docs/en/" target="new">Lorem ipsum</a>. The quick brown fox jumps over the lazy dog.
{% endblocktrans %}

而对于德语,我需要将http://external/docs/de/ 作为超链接

{% blocktrans %}
Hello, how are you? <a href="http://external/docs/de/" target="new">Lorem ipsum</a>. The quick brown fox jumps over the lazy dog.
{% endblocktrans %}

虽然 django 文档中的示例仅适用于内部 URL。

{% if LANGUAGE_CODE == 'en' %}
  {% url 'views.doc.en' as urldoc %}
{% else %}
  {% url 'views.doc.de' as urldoc %}
{% endif %}
{% blocktrans %}
Hello, how are you? <a href={{ urldoc }} target="new">Lorem ipsum</a>. The quick brown fox jumps over the lazy dog.
{% endblocktrans %}

【问题讨论】:

    标签: python django django-templates


    【解决方案1】:

    您可以直接使用模板中带有{{ LANGUAGE_CODE }}的语言代码并将其添加到url中。例如:

    {% blocktrans %}
    Hello, how are you? <a href=http://external/docs/{{ LANGUAGE_CODE }}/ target="new">Lorem ipsum</a>. The quick brown fox jumps over the lazy dog.
    {% endblocktrans %}
    

    当用户选择英语时,{{ LANGUAGE_CODE }} 将是en。如果用户选择了德语{{ LANGUAGE_CODE }} 将是de

    因此,链接将是:

    【讨论】:

    • 但是,使用那个 sn-p,我该如何放置 if/else 语句?到目前为止,我的想法是为每个外部链接创建视图,并将 if/else 语句放在 blocktrans 标记之前。
    • 有了这个 sn-p 你不需要 is/else 语句,因为带有正确语言代码的 url 是用 {{ LANGUAGE_CODE }} 动态构建的
    【解决方案2】:

    到目前为止,我的解决方案是在 views.py 创建函数,它将重定向到外部 URL。

    @login_required
    def doc_en():
        return HttpResponseRedirect('http://external/docs/en')
    
    @login_required
    def doc_de():
        return HttpResponseRedirect('http://external/docs/de')
    

    【讨论】:

      猜你喜欢
      • 2021-08-07
      • 1970-01-01
      • 1970-01-01
      • 2013-07-11
      • 2011-03-20
      • 2012-02-16
      • 2013-08-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多