简体   繁体   English

Flask Javascript Array 显示在 html 中?

[英]Flask Javascript Array display in html?

I have an array being rendered into my Flask route.我有一个数组被渲染到我的 Flask 路由中。 I have it showing up via this code:我通过以下代码显示它:

      <script>
        var purchases = JSON.parse('{{ purchase | safe }}');
        console.log(purchases)
     </script>

Trying to loop through purchases, though, in the DOM with the code below and getting nothing.但是,尝试使用以下代码在 DOM 中循环购买,却一无所获。

            {% for p in purchases %}
                {{ p.MLSNumber }}
            {% endfor %}

The array is there, just can't seem to access it (here is an example of the console)数组在那里,只是似乎无法访问它(这是控制台的示例)

(9) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0: {BedsTotal: '2', ListPrice: 99500, MLSAreaMinor: 'Williams', MLSNumber: '7058585', PostalCode: '80821', …}
1: {BedsTotal: '1', ListPrice: 58000, MLSAreaMinor: 'Ramah', MLSNumber: '9555642', PostalCode: '64620', …}
2: {BedsTotal: '1', ListPrice: 90000, MLSAreaMinor: 'Unknown', MLSNumber: '1936385', PostalCode: '81006', …}

Where am I going wrong?我哪里错了?

As I understand you, you want to filter a list of homes based on an indication of the maximum price.据我了解,您想根据最高价格的指示过滤房屋列表。 In this case you can use JSON, but this is not absolutely necessary.在这种情况下,您可以使用 JSON,但这不是绝对必要的。 Especially if you don't want to load the data within an AJAX request, I would avoid that.特别是如果您不想在 AJAX 请求中加载数据,我会避免这种情况。

In the following example, form data is transmitted to the server, a dictionary you mentioned is filtered and the results are presented on the page.在下面的例子中,表单数据被传输到服务器,你提到的字典被过滤,结果呈现在页面上。
In contrast to you, I use a GET request for the sake of simplicity.与您相反,为了简单起见,我使用 GET 请求。 The values are sent as parameters within the URL.这些值作为 URL 中的参数发送。 But there is nothing against using a POST request to transport the form data in the request body and to protect it from the eyes of third parties.但是没有什么反对使用 POST 请求来传输请求正文中的表单数据并保护它免受第三方的注意。
With both variants, the input can be converted into a float when the request is made from the request object by specifying the type attribute.对于这两种变体,当通过指定 type 属性从请求对象发出请求时,可以将输入转换为浮点数。 It is also possible to specify a default value.也可以指定默认值。
I use a custom jinja2 filter to format the price.我使用自定义 jinja2 过滤器来格式化价格。

from flask import Flask
from flask import render_template, request
import pandas as pd

app = Flask(__name__)

@app.template_filter()
def format_currency(value):
    return "$ {:,.2f}".format(value)

df = pd.DataFrame.from_dict({
    'MLSNumber': [9504716, 4426383],
    'ListPrice': [659849.00, 1500000.00],
    'BedsTotal': [4, 4],
    'MLSAreaMinor': ['Greenways At Sand Creek', 'Keene Ranch'],
    'StreetNumber': [3819, 3231],
    'StreetName': ['Ivy Hill', 'Castle Butte'],
    'PostalCode': [80922, 80109],
    'TaxAmount': [200.00, 4967.00],
})

@app.route('/')
def index():
    price = request.args.get('income', 12000.00, type=float)

    items = df.to_dict(orient='records')
    items = [item for item in items if item['ListPrice'] <= price]

    return render_template('index.html', items=items, income=price)
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <div style="margin-bottom: 1.5rem;">
      <form>
        <div>
          <label for="income">Income</label>
          <input type="NUMBER" step="0.01" name="income" id="income" value="{{ '{:.2f}'.format(income) }}" />
        </div>
        <input type="submit" />
      </form>
    </div>

    <div>
      {% if items -%}
      <table>
        <thead>
          <tr>
            <th>StreetName</th>
            <th>StreetNumber</th>
            <th>PostalCode</th>
            <th>MLSNumber</th>
            <th>MLSAreaMinor</th>
            <th>ListPrice</th>
            <th>TaxAmount</th>
          </tr>
        </thead>
        <tbody>
          {% for item in items %}
          <tr>
            <td>{{item['StreetName']}}</td>
            <td>{{item['StreetNumber']}}</td>
            <td>{{item['PostalCode']}}</td>
            <td>{{item['MLSNumber']}}</td>
            <td>{{item['MLSAreaMinor']}}</td>
            <td>{{item['ListPrice'] | format_currency}}</td>
            <td>{{item['TaxAmount'] | format_currency}}</td>
          </tr>
          {% endfor %}
        </tbody>
      </table>
      {% else -%}
      <span>No items found.</span>
      {% endif %}
  </body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM