0

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:

  1. Have semantic tags for time.
  2. Don't have HTML within Python files: Backend developers should not have to deal with HTML
  3. 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

  1. The <time> tag gets escaped - and it would not be safe to use the safe jinja filter
  2. I don't know how to format pubdate here, because babel.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.

desertnaut
  • 57,590
  • 26
  • 140
  • 166
Martin Thoma
  • 124,992
  • 159
  • 614
  • 958
  • Why aren't you just formatting the date at the backend before rendering the template? – roganjosh Aug 11 '19 at 14:02
  • @roganjosh I've added this as "3rd try". I would have hoped that there is a solution where I don't have to pass the same information in multiple formats. – Martin Thoma Aug 11 '19 at 16:29
  • The alternative being to pass the same format once and get the template parser to fix the format twice? It's only offloading work elsewhere. _Somewhere_ this has to be processed, why in the template language? – roganjosh Aug 11 '19 at 17:17

0 Answers0