如何在Django模板中设置html lang属性?
我编写了一个 Django 应用程序,为德语用户提供翻译内容,为其他用户提供英语内容。目前我使用的基本模板包含:
<html lang="en">
显然,如果内容以德语形式提供,这会设置错误的lang
。
也许我可以尝试类似的方法
<html lang="{{ 'de' if request.LANGUAGE_CODE == 'de' else 'en' }}">
,但这感觉很笨拙,并且在添加更多语言的情况下难以维护。
将 设置为实际提供的语言的简单方法是什么?
I wrote a Django application that serves translated content for German users, and English content for everyone else. Currently I use a base template containing:
<html lang="en">
Obviously this sets the wrong lang
in case the content is served as German.
Possibly I could try something like
<html lang="{{ 'de' if request.LANGUAGE_CODE == 'de' else 'en' }}">
but this feels clumsy and hard to maintain in case more languages are added.
What would be a simple way to set <html lang>
to the actual language served?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我想通了。
get_current_language 标记包含首选语言用户的。
对我来说,文档并没有立即明确表示“首选语言”不是“Accept-Language”HTTP 标头中最顶层的语言,而是始终是最符合用户偏好的
setting.LANGUAGES
语言。就我而言,
settings.py
包含:如果用户更喜欢 Italien,则
get_current_language
仍将是en
。对于在端口 8000 上本地运行的 Django 应用程序,您可以尝试以下操作:输出类似于:
如果请求中没有提供首选语言,则结果是相同的。因此不需要
|default:'en'
。您可以使用以下方法进行测试:I figured it out.
The get_current_language tag contains the preferred language of the user.
To me the documentation did not make it clear immediately that "preferred language" is not the topmost language from the "Accept-Language" HTTP header but always the language from
setting.LANGUAGES
that best matches the user's preference.In my case
settings.py
contains:If the user however prefers for example Italien,
get_current_language
will still been
. With the Django application running locally on port 8000, you can try this with for example:The output is something like:
If no preferred language is provided with the request, the result is the same. So there is no need for a
|default:'en'
. You can test this with:您可以尝试此操作,
这将添加
request.LANGUAGE_CODE
(如果可用),否则会将默认值设置为 enYou can try this
this will add
request.LANGUAGE_CODE
if it available or it will set default value as en