Within a jinja template, I have the following string
# English
<p>by John Smith on <time pubdate="pubdate" datetime="2019-01-30T20:54:55">January 30, 2019</time></p>
# German
<p>am <time pubdate="pubdate" datetime="2019-01-30T20:54:55">30. Januar 2019</time> von John Smith veröffentlicht</p>
1st try
Having the date formatted / localized in the backend:
# In the routes.py:
pubdate = '<time pubdate="pubdate" datetime="{date_iso}">{date_localized}</time>' \
.format(date_iso=pubdate.isoformat(),
date_localized=flask_babel.dates.format_date(pubdate))
# In the jinja template:
<p>{{_('by %(author)s on %(pubdate)s', author=author, pubdate=pubdate)}}</p>
But then I have to care about HTML outside of a Jinja template which I would like to avoid.
What I would like to achieve:
- ✓ Have semantic tags for time.
- ✗ Don't have HTML within Python files: Backend developers should not have to deal with HTML
- ✓ Don't have HTML within
pot
files: Translators should not have to deal with HTML
2nd try
I tried
<p>{{_('by %(author)s on %(pubdate)s',
author=author,
pubdate='<time pubdate="pubdate" datetime="{pubdate}">{pubdate}</time>'.format(pubdate=pubdate))}}</p>
This has multiple problems
- The
<time>
tag gets escaped - and it would not be safe to use thesafe
jinja filter - I don't know how to format
pubdate
here, becausebabel.dates.format_datetime
is not known here
3rd try
@app.route("/")
def index():
print(_('Hello World!'))
flash(_('Hello World!'))
pubdate = datetime.datetime.now()
return render_template("main.html",
pubdate=pubdate,
author='John Smith',
date_localized=flask_babel.dates.format_date(pubdate))
main.html:
<p>{{_('by %(author)s on %(pubdate)s', author=author, pubdate='<time pubdate="pubdate" datetime="{pubdate}">{date_localized}</time>'.format(pubdate=pubdate, date_localized=date_localized))}}</p>
displayed as:
by John Smith on <time pubdate="pubdate" datetime="2019-08-11 18:26:54.428453">11.08.2019</time>
So the problem is that the tag gets escaped. But I probably shouldn't use safe
as <
or >
could be within the translation.
See Github for a minimal example.