Django: How to get language code in template?

后端 未结 3 1214
你的背包
你的背包 2021-02-01 01:49

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\"

3条回答
  •  旧时难觅i
    2021-02-01 01:57

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

    Put this somewhere:

    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.)

    However, it does exist, as the inbuilt template context processor django.template.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
        return {
            'LANGUAGES': settings.LANGUAGES,
            'LANGUAGE_CODE': translation.get_language(),
            'LANGUAGE_BIDI': translation.get_language_bidi(),
        }
    

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

提交回复
热议问题