动态网址和Jinja模板

时间:2019-09-26 22:45:29

标签: python flask jinja2 pymongo

我一直在尝试创建用户界面以从数据库中过滤出结果。重要的是我希望过滤器是“加性的”。因此,如果用户选择一个过滤器,页面将重定向并显示结果。之后,用户可以选择另一个过滤器,结果将缩小为两个过滤器。对于任何数量的过滤器,此操作都应继续。

这就是现在的样子

@app.route('/')
def home():

    kind = request.args.get('kind')
    price = request.args.get('price')
    category = request.args.get('category')

    filters = {}
    if price is not None: filters['params.price'] = {'$lt' : int(price) }
    if kind is not None: filters['kind'] = kind
    if category is not None: filters['category'] = category

    posts = db.collection.find(filters)

    return render_template('home.html', posts=posts)

以及使用jinja2模板的href链接

<li><a href="{{ url_for ('home', kind='m') }}">Label</a></<li>
<li><a href="{{ url_for ('home', price=50000)}}">Label</a></li>
<li><a href="{{ url_for ('home', category='p') }}">Label</a></li>
... many more similar links

当前,它用作URL的替代。如果我单击其中任何链接,它将替换整个URL并使用链接中的变量。

first link: http://127.0.0.1/?kind=m
second link: http://127.0.0.1/?price=5000
third link: http://127.0.0.1/?category=p

我想要做的是追加查询-如果我单击任何链接,它会记住先前选择的过滤器并“添加”最后单击的链接。下面我展示了我期望它如何工作。

first link: http://127.0.0.1/?kind=m
second link: http://127.0.0.1/?kind=m?price=50000
second link: http://127.0.0.1/?kind=m?price=50000?category=p

1 个答案:

答案 0 :(得分:0)

您可以将所有过滤器值(最初为None)传递给视图,并将它们作为参数添加到url_for调用中。 None的过滤器不会包含在链接中。