librelist archives

« back to archive

dumb and happy design for translatable blog posts in a flask app

dumb and happy design for translatable blog posts in a flask app

From:
Joshua Bronson
Date:
2011-10-24 @ 23:00
_posts.html:


{# post bodies #}{% macro _post1_body() %}<p>{% trans %}Hi from post
1{% endtrans %}</p>{% endmacro %}
{# slug->post map (newest posts first) #}{% set posts = OrderedDict([
  ('2011-10-24/first-post', {
    'title': _('First post!'),
    'updated': '2011-10-24T00:00:00Z',
    'body': _post1_body(),
    }),]) -%}




news.html:

{% from '_macros.html' import render_post with context %}{% from
'_posts.html' import posts with context %}{% if slug %}
  {{ render_post(slug, posts[slug]) }}{% else %}  <ul>  {% for slug,
post in posts.iteritems() %}    <li>{{ render_post(slug, post) }}</li>
 {% endfor %}  </ul>{% endif %}



views.py:

def news(slug=None):
    if slug is None:
        return render_template('news.html')
    tmpl = app.jinja_env.get_template('_posts.html')
    posts = tmpl.module.posts
    if slug in posts:
        return render_template('news.html', slug=slug)
    abort(404)



The routes that map to news look like "/news/" and "/news/<path:slug>", and
are added to a blueprint with a url prefix like "/<any(en, de,
...):langcode>/".

Advantages: this design allows the posts to all be defined in the _posts
template, which has all Jinja2's facilities (markup, filters, babel
integration, etc.), and can be imported from other templates that need it
(e.g. news.atom). Good if you don't need anything fancier than this
(filtering by date, tags, etc.) and want a correspondingly lightweight
solution.

I just wanted to run this design past the list, since reaching into the
template's posts definition from Python to do the 404 check felt funny.

(Btw, if the _posts template needed to access common variables like g,
request, config, etc., tmpl.module.posts would have to be replaced
with tmpl.make_module(app.template_context_processors[None][0]()).posts
above. Not so pretty...)

Thanks for reading.

Re: dumb and happy design for translatable blog posts in a flask app

From:
Joshua Bronson
Date:
2011-10-24 @ 23:13
On Mon, Oct 24, 2011 at 7:00 PM, Joshua Bronson <jabronson@gmail.com> wrote:

> I just wanted to run this design past the list, since reaching into the
> template's posts definition from Python to do the 404 check felt funny.
>

Rather than doing this on every request, you could instead do this once at
route-creation time, e.g.

tmpl = app.jinja_env.get_template('_posts.html')
route = "/news/<any(%s):slug>" % ", ".join(tmpl.module.posts)


leaving the 404s to werkzeug.

Then the news view becomes just:

def news(slug=None):
    return render_template('news.html', slug=slug)