如何在模板中获取语言代码

如何在模板中获取语言代码

本文介绍了Django:如何在模板中获取语言代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在django模板中是否有一些gettin语言代码的全局变量,或者至少通过视图传递它?
如下: {{LANG}} 应该产生en,例如..
当人们使用 request.LANGUAGE_CODE 。

Is there's some global variable for gettin' language code in django template or atleast passing it through view?something like: {{ LANG }} should produce "en" for example..I really not comfortable when people using request.LANGUAGE_CODE.

详细解释将不胜感激=)

Detailed explanation would be appreciated =)

推荐答案

不存在,您需要编写一个。以下是您如何做到这一点。

If it didn't already exist, you would need to write a template context processor. Here's how you'd do that.

将此放在某个地方:

def lang_context_processor(request):
    return {'LANG': request.LANGUAGE_CODE}

然后,添加设置。这样做:

And then, add a reference to it the TEMPLATE_CONTEXT_PROCESSORS setting. Something like this:

from django.conf import global_settings

TEMPLATE_CONTEXT_PROCESSORS = global_settings.TEMPLATE_CONTEXT_PROCESSORS + (
    'myproject.myapp.templatecontext.lang_context_processor',
)

(我推荐添加到全局设置,因为这意味着当一个新的上下文处理器添加到默认值时,您不会意外中断事件。)

(I recommend adding to the global setting because it means you don't break things accidentally when a new context processor is added to the defaults.)

但是,它确实存在,因为内置模板上下文处理器。您可以使用 LANGUAGE_CODE 访问它。

However, it does exist, as the inbuilt template context processor django.core.context_processors.i18n. You can access it as LANGUAGE_CODE.

纯粹为了感兴趣,这里是该功能的定义:

Purely for interest, here's the definition of that function:

def i18n(request):
    from django.utils import translation

    context_extras = {}
    context_extras['LANGUAGES'] = settings.LANGUAGES
    context_extras['LANGUAGE_CODE'] = translation.get_language()
    context_extras['LANGUAGE_BIDI'] = translation.get_language_bidi()

    return context_extras

确保您使用的是 RequestContext 用于您的模板呈现,而不是一个简单的上下文,否则它将无法正常工作。

Make sure that you're using a RequestContext for your template rendering, not a plain Context, or it won't work.

这篇关于Django:如何在模板中获取语言代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 02:31