【问题标题】:For loop in flask not visible in html page烧瓶中的for循环在html页面中不可见
【发布时间】:2017-07-18 12:47:37
【问题描述】:

我实际上是想在烧瓶模板中打印一个 for 循环,我使用了不同的方法但 html 页面上没有出现任何内容,python 代码工作正常,我只是不知道如何用 jinja 实现它。

Views.py

@app.route('/results', methods=['POST', 'GET'])
def results():

    keyword = {'keyword': request.args.get('keyword')} # First Method
    keyword = request.form['keyword'] # Second Method

    num_tweets=5

    for tweet in tweepy.Cursor(api.search,q=str(keyword)+
        " -filter:retweets",
        result_type='recent',
        lang="en").items(num_tweets):
        clean = re.sub(r"(?:@\S*|#\S*|http(?=.*://)\S*)", "", tweet.text)
        result = cool.api(clean)
    return render_template('pages/results.html')

结果.html

<body>
<div>

{{ result }}
{{ clean }}

</div>        
</body>

【问题讨论】:

    标签: python flask jinja2


    【解决方案1】:

    但这些都没有任何意义。

    您在一系列推文中循环。在该循环中,您反复用一个值覆盖 resultclean 变量。因此,在循环结束时,您将获得最终变量。

    当然,这一切都没有区别,因为您甚至没有将这些变量发送到要渲染的模板,所以模板当然是空白的。

    您需要将值累积到一个列表中。然后,您需要将列表发送到模板。最后,需要遍历模板中的列表。

    results = []
    for tweet in ...:
        clean = re.sub(r"(?:@\S*|#\S*|http(?=.*://)\S*)", "", tweet.text)
        result = cool.api(clean)
        results.append((clean, result))
     return render_template('pages/results.html', results=results)
    

    ...

    {% for clean, result in results %}
        {{ clean }}
        {{ result }}
     {% endfor %}
    

    【讨论】:

      【解决方案2】:

      您没有传递任何要呈现的数据。

      results = list() 
      for tweet in tweepy.Cursor(api.search,q=str(keyword)+
          " -filter:retweets",
          result_type='recent',
          lang="en").items(num_tweets):
              clean = re.sub(r"(?:@\S*|#\S*|http(?=.*://)\S*)", "", tweet.text)
              result = cool.api(clean)
              results.append((result, clean)) 
      return render_template('pages/results.html', results=results)
      

      你还需要在 Jinja2 中实现一个循环

      {% for result in results %} 
      {{ result[0] }}
      {{ result[1] }}
      {% endfor %} 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-06-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-31
        • 2011-12-02
        • 2021-05-03
        相关资源
        最近更新 更多