Last active
February 3, 2021 13:02
-
-
Save simonbru/474aca7d7d8745c32f1d836ed77c849c to your computer and use it in GitHub Desktop.
Context manager to emphasize Django translated strings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import contextlib | |
from django.utils import translation | |
from django.utils.safestring import SafeData, SafeText | |
def prefix_decorator(function): | |
def prefix_wrapper(*args, **kwargs): | |
result = function(*args, **kwargs) | |
wrapped_result = "[[ " + result + " ]]" | |
# if isinstance(result, SafeData): | |
# wrapped_result = SafeText(wrapped_result) | |
return wrapped_result | |
return prefix_wrapper | |
class DebugTrans: | |
methods = [ | |
"gettext", | |
"ugettext", | |
"ngettext", | |
"ungettext", | |
"pgettext", | |
"npgettext", | |
] | |
def __init__(self, trans): | |
self.trans = trans | |
def __getattr__(self, real_name): | |
method = getattr(self.trans, real_name) | |
if real_name in self.methods: | |
method = prefix_decorator(method) | |
return method | |
@contextlib.contextmanager | |
def debug_trans(): | |
orig_trans = translation._trans | |
translation._trans = DebugTrans(orig_trans) | |
yield | |
translation._trans = orig_trans |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment