You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
This repository has been archived by the owner on Jul 14, 2020. It is now read-only.
Usually there is some kind of global containing the current user's locale. Let's imagine a Flask application where I can get the current locale by calling get_locale().
Right now the only way to make use of this in MongoKit seems to be calling foo.set_lang(get_locale()) on every single object. This gets especially ugly when retrieving multiple objects and passing them to a template as a a list.
It would be much nicer if there was e.g. a default_lang setting which could be set to a callable that would be invoked whenever the current language needs to be retrieved.
The text was updated successfully, but these errors were encountered:
I'm now using this custom Document subclass to get the behaviour I was looking for:
from contextlib import contextmanager
from flask import current_app
from flask.ext.babel import get_locale
from flask.ext.mongokit import Document
class CustomDocument(Document):
"""Base MongoKit document with some useful features
- Fallback language taken from app config
- Active language taken from current locale
- Context manager to temporarily change the language
"""
def __init__(self, *args, **kwargs):
self._current_lang_override = None
super(CustomDocument, self).__init__(*args, **kwargs)
self._current_lang = None
self._fallback_lang = current_app.config['BABEL_DEFAULT_LOCALE']
@property
def _current_lang(self):
if self._current_lang_override is not None:
return self._current_lang_override
return get_locale().language
@_current_lang.setter
def _current_lang(self, lang):
self._current_lang_override = lang
@contextmanager
def change_lang(self, lang):
"""Temporarily changes the active language"""
old_lang = self._current_lang_override
self.set_lang(lang)
yield
self.set_lang(old_lang)
Usually there is some kind of global containing the current user's locale. Let's imagine a Flask application where I can get the current locale by calling
get_locale()
.Right now the only way to make use of this in MongoKit seems to be calling
foo.set_lang(get_locale())
on every single object. This gets especially ugly when retrieving multiple objects and passing them to a template as a a list.It would be much nicer if there was e.g. a
default_lang
setting which could be set to a callable that would be invoked whenever the current language needs to be retrieved.The text was updated successfully, but these errors were encountered: