Django:在模板中显示当前区域设置

时间:2020-12-11 20:22:07

I need to embed the current locale in a Django template's output (as part of a URL to be precise). I know that I can access the current language as {{ LANGUAGE_CODE }} if I { load i18n } but is there a similar way to access the current locale?

我需要在Django模板的输出中嵌入当前的语言环境(准确地说,作为URL的一部分)。我知道如果我{load i18n}我可以访问当前语言{{LANGUAGE_CODE}}但是有类似的方式来访问当前的语言环境吗?

I suppose I could use to_locale() in the view logic and put it in the context for the template, but I'm looking for something more generic that might be part of the Django framework itself. Is there such a syntax?

我想我可以在视图逻辑中使用to_locale()并将其放在模板的上下文中,但我正在寻找可能是Django框架本身一部分的更通用的东西。有这样的语法吗?

3 个解决方案

#1


26  

I solved this by including code below in the template

我通过在模板中包含以下代码解决了这个问题

{% load i18n %}
{% get_current_language as LANGUAGE_CODE %}

and the variable LANGUAGE_CODE has the value you want (see also django docs for an example usage).

并且变量LANGUAGE_CODE具有您想要的值(有关示例用法,另请参阅django docs)。

#2


9  

You might want to write your own context processor, which would call to_locale and automatically populate the context with the result -- it would just be something like this.

您可能希望编写自己的上下文处理器,它将调用to_locale并自动使用结果填充上下文 - 它就是这样的。

from django.utils.translation import to_locale, get_language
def locale(request):
    return {'LOCALE': to_locale(get_language())}

#3


2  

I thought of implementing my own custom template tag that would simply output to_locale(get_language()) but the answer above is easier to implement so I like it better.

我想实现我自己的自定义模板标签,只需输出to_locale(get_language()),但上面的答案更容易实现,所以我更喜欢它。

#1


26  

I solved this by including code below in the template

我通过在模板中包含以下代码解决了这个问题

{% load i18n %}
{% get_current_language as LANGUAGE_CODE %}

and the variable LANGUAGE_CODE has the value you want (see also django docs for an example usage).

并且变量LANGUAGE_CODE具有您想要的值(有关示例用法,另请参阅django docs)。

#2


9  

You might want to write your own context processor, which would call to_locale and automatically populate the context with the result -- it would just be something like this.

您可能希望编写自己的上下文处理器,它将调用to_locale并自动使用结果填充上下文 - 它就是这样的。

from django.utils.translation import to_locale, get_language
def locale(request):
    return {'LOCALE': to_locale(get_language())}

#3


2  

I thought of implementing my own custom template tag that would simply output to_locale(get_language()) but the answer above is easier to implement so I like it better.

我想实现我自己的自定义模板标签,只需输出to_locale(get_language()),但上面的答案更容易实现,所以我更喜欢它。