在我的網站上使用Flask + Jinja2和Flask-Babel進行翻譯。該網站有兩種語言(取決於URL),我想添加一個鏈接在它們之間切換。爲了正確地做到這一點,我需要獲取當前語言環境的名稱,但是我沒有在文檔中找到這樣的功能。它是否存在?獲取Jinja2中的當前語言環境
2
A
回答
3
最後,我使用的這個解決方案:添加get_locale
功能,應該無論如何所定義,的Jinja2全局變量,然後調用它在模板等任何其他功能。
1
您有責任將用戶的區域設置存儲在數據庫的會話中。 Flask-babel
不會爲你做這個,所以你應該實現get_locale
方法flask-babel
能夠找到你的用戶的區域設置。
這是從flask-babel
文檔的get_locale
一個例子:
from flask import g, request
@babel.localeselector
def get_locale():
# if a user is logged in, use the locale from the user settings
user = getattr(g, 'user', None)
if user is not None:
return user.locale
# otherwise try to guess the language from the user accept
# header the browser transmits. We support de/fr/en in this
# example. The best match wins.
return request.accept_languages.best_match(['de', 'fr', 'en'])
+0
是的,我已經實現了這樣的get_locale函數,它返回一個語言環境取決於URL。但是如何獲得Jinja模板中的活動請求區域設置? – aplavin 2013-05-05 12:02:22
相關問題
- 1. Thmeleaf獲取當前語言環境
- 2. django:獲取templatetag中的當前語言環境
- 3. 如何獲取symfony 2.3中的當前語言環境?
- 4. 獲取當前在C++中設置的全局語言環境?
- 5. 如何使用LocaleInfo獲取GWT中的當前語言環境
- 6. 在C中獲取當前語言環境的字符集?
- 7. 在Perl中獲取當前語言環境名稱
- 8. 十月CMS如何獲取當前的語言環境名稱?
- 9. 如何從Spring MVC獲取當前使用的語言環境?
- 10. 如何在django上獲取當前語言環境的「short_date_format」?
- 11. 從當前線程文化獲取語言環境代碼
- 12. Android:如何在特定語言環境中獲取字符串而不更改當前語言環境
- 13. symfony2.0.0獲取security.yml中的語言環境
- 14. 在片段中獲取語言環境
- 15. 獲取TYPO3當前語言
- 16. 在Laravel的提供者類中獲取語言環境語言
- 17. 在PHP中獲取語言的默認語言環境
- 18. 的Grails/SpringSecurity:獲取語言環境LogoutHandler
- 19. 獲取語言環境的貨幣
- 20. PHP獲取語言環境的名稱
- 21. 在另一個Windows進程中獲取當前線程的語言環境
- 22. 從當前語言環境獲取Grails中的所有國際字符串?
- 23. 獲取C#中的當前語言
- 24. 獲取當前TTS語音的語言
- 25. 在iOS 5上獲取語言環境
- 26. Symfony 2:獲取用戶語言環境
- 27. 如何獲取當前語言環境的一週的第一天? (PHP/L8N)
- 28. 爲什麼Android有自己的方式來獲取當前的語言環境?
- 29. 獲取網站訪問者的語言環境(語言)?
- 30. 從Java語言環境獲取語言的字母表
你是怎麼加入jinja2全局變量的?我試着做e = Environment,例如:{'get_locale':get_locale} – 8oh8 2017-03-21 02:00:36