首页 > 解决方案 > Set a variable in jinja by querying a list

问题描述

So, lets say I have a route like following

@app.route('/get_list/<int:q>')
def get_list(q):
   return [1,2,3, q]

and in html, I want to get this list (without passing thru template)

I am trying to do something like

{% set variables = "url_for('get_list', q=1)" %}
<ul>
{% for var in variables%}
<li> {{var}} </li>
{%endfor%}
</ul>

But, well the set variables is wrong. Is there a way to query the server and get those variables rather than passing thru the "render_template" ? Thanks

标签: flaskjinja2

解决方案


您应该对您的数据进行jsonify处理。

虽然,我不明白您想从数组中检索什么,但我只检索通过 GET 请求传递的一个值,如下所示:

from flask import Flask, jsonify

app = Flask(__name__)


@app.route('/get_list/<int:q>')
def get_list(q):
    dummy_data = [44, 55, 33]

    # dummy_data.index(q) return position in array of q value
    # so if you pass 55, it will return 1
    result_from_query = dummy_data[dummy_data.index(q)]

    return jsonify(result_from_query)

推荐阅读