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

问题描述:

我需要将当前语言环境嵌入Django模板的输出(作为URL的一部分)。如果我 {load i18n} $,我知道我可以访问当前的语言作为 {{LANGUAGE_CODE}} c $ c>但是有没有类似的方式访问当前的区域设置

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?

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

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?

我通过在模板中包含下面的代码来解决这个问题

I solved this by including code below in the template

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

,变量 LANGUAGE_CODE 具有所需的值(另见 django docs 为例)

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