【问题标题】:how to loop variables from Python controller to JavaScript with flask?如何使用烧瓶将变量从 Python 控制器循环到 JavaScript?
【发布时间】:2018-06-02 13:14:54
【问题描述】:

我想在网站上显示嵌套内容:

例如:

短语 1:苹果

包含短语 1 的推文:我喜欢苹果。

短语2:香蕉

包含短语 2 的推文:香蕉是最好的。

我在python控制器中的数据集是[["apple","包括短语1:我喜欢苹果。"],["banana","banana is best."]]

我的 html 文件是:

{% extends "layout.html" %}
{% block body %}
<p>Click the button to loop from 1 to 6, to make HTML headings.</p>
<button onclick="myFunction2()">Try it</button>
<div id="demo"></div>
<script>
function myFunction2() {
    var x ="", i;    
    for (i=1; i<=2; i++) {
        x = x +"<h2 class=\"phrase\">phrase"+i+":"+"{{phrases[i]}}"+"</h2>";
    }
    document.getElementById("demo").innerHTML = x;
}
</script>
{% endblock %}

但它只显示:

点击按钮从 1 到 6 循环,制作 HTML 标题。

短语1:

短语2:

没有显示任何短语。但是当我使用 {{phrases[1]}} {{phrases[2]}} 时,它可以正常显示。我不能用 i 循环每个变量吗?

【问题讨论】:

  • 您对这里的工作方式有一个非常严重的误解。您不可能在 Jinja 模板标签中使用 JavaScript 变量。
  • 对不起我的无知

标签: python html web flask web-development-server


【解决方案1】:

您可以将ajax 与您的flask 后端一起使用。首先,创建 HTML 模板来显示按钮,然后创建第二个更小的模板来循环数据集:

home.html:

<html>
  <head>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  </head>
 <body>
   <p>Click the button below to access tweet list from 1-6</p>
   <button class='tweets'>View Tweets</button>
   <div id='results'></div>
 </body> 
<script>
  $(document).ready(function() {
    $('.tweets').click(function() {
     $.ajax({
     url: "/get_tweets",
      type: "get",
      data: {'tweets': 'yes'},
      success: function(response) {
       $("#results").html(response.result);
       },
       error: function(xhr) {
       //pass
      }
     });
   });
 });
</script>
</html>

display_data.html:

{%for tweet in tweets%}
  <div class='tweet' style='border:solid;border-color:black'>
    <p>{{tweet.title}}: {{tweet.phrase}}</p>
    <p>{{tweet.including}}</p>
  </div>
{%endfor%}

然后,在您的 .py 文件中,创建必要的 flask 路由:

import flask
import typing
app = flask.Flask(__name__)
class Tweet(typing.NamedTuple):
  phrase:str
  including:str
  title:str

@app.route('/tweets', methods=['GET'])
def tweets():
  return flask.render_template('home.html')

@app.route('/get_tweets')
def view_tweets():
   datasets = [["apple","including phrase1: I like apple."],["banana","banana is best."]]
   new_set = [Tweet(a, b, f'phrase{i}') for i, [a, b] in enumerate(datasets, start=1)]
   return flask.jsonify({"result":flask.render_template('display_data.html', tweets = new_set)})

【讨论】:

    猜你喜欢
    • 2020-12-21
    • 2017-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-20
    相关资源
    最近更新 更多