Skip to content

Instantly share code, notes, and snippets.

@vmagamedov
Last active August 25, 2020 14:11
Show Gist options
  • Save vmagamedov/a16e4dee92530a68f728253d62388fd7 to your computer and use it in GitHub Desktop.
Save vmagamedov/a16e4dee92530a68f728253d62388fd7 to your computer and use it in GitHub Desktop.
Allows easy rich text translation
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