Last active
August 25, 2020 14:11
-
-
Save vmagamedov/a16e4dee92530a68f728253d62388fd7 to your computer and use it in GitHub Desktop.
Allows easy rich text translation
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 re | |
from functools import partial | |
from markupsafe import Markup, escape | |
_RE = re.compile(r'\[([\w\s]*)\|\s*([a-z0-9_]+)\s*\]') | |
def rich_text(text, **params): | |
data = {} | |
def repl(m): | |
""" | |
Replaces [text|key] with {key} and collects data for insertion into text | |
""" | |
content, key = m.groups() | |
data[key] = params[key](content) | |
return f'{{{key}}}' | |
# preserve type of text: Markup or str | |
text = type(text)(_RE.sub(repl, text)) | |
return text.format(**data) | |
def test(): | |
def _(value): | |
return value | |
def link_to(url, text): | |
return Markup('<a href="{url}">{text}</a>').format(url=url, text=text) | |
result = rich_text( | |
Markup(_('Перейдите в [кабинет продавца|cabinet_url] и активируйте Prosale!')), | |
cabinet_url=partial(link_to, 'https://prom.ua/'), | |
) | |
assert escape(result) == ( | |
'Перейдите в <a href="https://prom.ua/">кабинет продавца</a>' | |
' и активируйте Prosale!' | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment