如何收拾这个Jinja2的和/或布尔表达式(how to clean up this jinja2

2019-09-16 23:12发布

{% block content %}
    {% for blog_dict in blogs|sort(reverse=True,attribute='date') if ((not file_name_filter) or blog_dict.filename==file_name_filter) and ((not category_filter) or blog_dict.category==category_filter) %}
        <div id="post{{blog_dict.post_number}}-{{blog_dict.link_name}}">
            {{blog_dict.date.strftime("%Y-%m-%d")}}
            <a href="/posts/{{blog_dict.filename}}"><h1>{{blog_dict.heading}}</h1></a>
            <!-- Place this tag where you want the +1 button to render -->
            <div class="g-plusone" data-href="/posts/{{blog_dict.filename}}"></div>
            {{blog_dict.post|safe}}
        </div>
        <br />
        <br />
        <br />
        <img src="/images/page_divider.gif"><br />
    {% endfor %}
{% endblock %}

正如你所看到的表情也越来越凌乱:

{% for blog_dict in blogs|sort(reverse=True,attribute='date') if ((not file_name_filter) or blog_dict.filename==file_name_filter) and ((not category_filter) or blog_dict.category==category_filter) %}

我尝试另一种选择是把两个嵌套如果在循环语句采取两个滤波器的照顾,但随后嵌套了较大。

什么是最优雅的?

Answer 1:

正如约翰·凯斯在评论中提到的,我添加了一个过滤器:

def blog_filter(blogs, file_name_filter, category_filter):
    if file_name_filter:
        blogs = (d for d in blogs if d['filename'] == file_name_filter)
    if category_filter:
        blogs = (d for d in blogs if d['category'] == category_filter)
    return blogs

这被添加到Jinja2的environment.filters字典

myconfig = {}
myconfig['webapp2_extras.jinja2'] =  {'template_path': ['templates','blog_posts'],
                                      'filters': {'blog_filter': blog_filter}}

app = webapp2.WSGIApplication(_routes,
    debug=True,
    config = myconfig)

表达式变为:

{% for blog_dict in blogs|blog_filter(file_name_filter,category_filter)|sort(reverse=True,attribute='date') %}

我还能够使用此过滤器的其他地方,如我的身边菜单:

{% for month, blog_dicts in blogs|blog_filter(False, category_filter)|groupby('date.month')|sort(reverse=True,attribute='grouper') %}

请注意我用的Jinja2包装(从webapp2_extras进口Jinja2的),它是在我的basehandler缓存属性

class BaseHandler(webapp2.RequestHandler):
    @webapp2.cached_property
    def jinja2(self):
        return jinja2.get_jinja2(app=self.app)

    def render_template(self, filename, **kwargs):
        #call self.response.write(self.jinja2.render_template(..)


文章来源: how to clean up this jinja2 and/or boolean expression