简体   繁体   English

使用 JavaScript 在 HTML 中对 Python/Flask 中动态呈现的表格进行排序

[英]Sort dynamically rendered table from Python/Flask in HTML using JavaScript

This is my first time building a web app and I wanted to start from scratch to learn the basics.这是我第一次构建 Web 应用程序,我想从头开始学习基础知识。 So I had a Python script that I wanted to practice with that printed tables of data on the terminal and decided to use Flask, HTML, CSS, JS to display that table on a web page.所以我有一个 Python 脚本,我想在终端上使用打印的数据表来练习,并决定使用 Flask、HTML、CSS、JS 在网页上显示该表。 I got that working so far.到目前为止,我已经开始工作了。

Now, I want to sort that table by clicking on the table headers.现在,我想通过单击表格标题对该表格进行排序。

This is the overall breakdown of my code and what I got up to so far:这是我的代码的整体细分以及到目前为止我所做的:

Python script Python脚本

from flask import Flask, render_template, request, url_for
app = Flask(__name__)

def get_table():
...
return dict    //returns list of dictionaries, for example... 
               //dict = [{'name':'Joe','age':'25'},
               //        {'name':'Mike','age':'20'}, 
               //        {'name':'Chris','age':'29'}] 



@app.route("/")
def home():
    return render_template('home.html')


@app.route("/table", methods = ['POST','GET'])
def table():
    if request.method == 'GET':       //When button pressed on homepage
        dict_table = get_table()      //return list of dictionaries of names and ages
        return render_template('table.html', dict_table=dict_table)

if __name__ == '__main__':
    app.run(debug=True)

HTML file table.html HTML 文件 table.html

<!DOCTYPE html>
<html>
<head>
    <title>Display Table</title>
    <script type="text/javascript" src="/scripts/app.js"></script>
</head>
<body>
        <table id="table">
        {% if dict_table %}
        <tr>
            {% for key in dict_table[0] %}
                <th onclick="sortTable(1)" style="cursor:crosshair">{{ key }}</th>
            {% endfor %}
        </tr>
        {% endif %}

        {% for dict in dict_table %}
        <tr>
            {% for value in dict.values() %}
                <td>{{ value }}</td>
            {% endfor %}
        </tr>
        {% endfor %}
    </table>
</body>
</html>

So the table displays correctly on my web browser.所以表格在我的网络浏览器上正确显示。 I used the sort function they taught on the W3 schools website in my app.js script.我在我的 app.js 脚本中使用了他们在 W3 学校网站上教授的排序功能。

app.js应用程序.js

function sortTable(n) {
  var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
  table = document.getElementById("myTable");
  switching = true;
  //Set the sorting direction to ascending:
  dir = "asc"; 
  /*Make a loop that will continue until
  no switching has been done:*/
  while (switching) {
    //start by saying: no switching is done:
    switching = false;
    rows = table.rows;
    /*Loop through all table rows (except the
    first, which contains table headers):*/
    for (i = 1; i < (rows.length - 1); i++) {
      //start by saying there should be no switching:
      shouldSwitch = false;
      /*Get the two elements you want to compare,
      one from current row and one from the next:*/
      x = rows[i].getElementsByTagName("TD")[n];
      y = rows[i + 1].getElementsByTagName("TD")[n];
      /*check if the two rows should switch place,
      based on the direction, asc or desc:*/
      if (dir == "asc") {
        if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
          //if so, mark as a switch and break the loop:
          shouldSwitch= true;
          break;
        }
      } else if (dir == "desc") {
        if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
          //if so, mark as a switch and break the loop:
          shouldSwitch = true;
          break;
        }
      }
    }
    if (shouldSwitch) {
      /*If a switch has been marked, make the switch
      and mark that a switch has been done:*/
      rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
      switching = true;
      //Each time a switch is done, increase this count by 1:
      switchcount ++;      
    } else {
      /*If no switching has been done AND the direction is "asc",
      set the direction to "desc" and run the while loop again.*/
      if (switchcount == 0 && dir == "asc") {
        dir = "desc";
        switching = true;
      }
    }
  }
}

This is the example I got from https://www.w3schools.com/howto/howto_js_sort_table.asp这是我从https://www.w3schools.com/howto/howto_js_sort_table.asp得到的例子

These are my issues so far到目前为止,这些是我的问题

  1. When I call that function sortTable, in the example they feed in the parameters 0 and 1 for sortTable(n) because their table is not dynamically rendered like mine.当我调用该函数 sortTable 时,在示例中,它们为 sortTable(n) 提供参数 0 和 1,因为它们的表不像我的那样动态呈现。 How do I handle this situation if im trying to use that function to sort my table since my table is dynamically created?如果我尝试使用该函数对我的表进行排序,因为我的表是动态创建的,我该如何处理这种情况? I'm referring to the line我指的是这条线in my HTML file.在我的 HTML 文件中。 I can't find sources where they teach how to handle this scenario and I would like to learn.我找不到他们教如何处理这种情况的来源,我想学习。
  2. If I feed it a parameter 1, when I click on my table header, nothing happens.如果我给它一个参数 1,当我点击我的表格标题时,什么也没有发生。 Can someone guide me towards where my mistake is and how I can fix it?有人可以指导我了解我的错误在哪里以及如何解决吗? I'm thinking it's because the table gets created in the loop after the headers are created so it has nothing to iterate over.我认为这是因为表是在创建标题后在循环中创建的,因此它没有任何可迭代的内容。

I would like it if someone could guide me through this.如果有人可以指导我完成此操作,我会很高兴。 I'm also open to hearing if there are better ways for me to do this as well, as long as it's not overly complicated and involve installing external applications like some solutions I've seen to similar problems like this (since i'm just a beginner and trying to learn).我也很乐意听取我是否有更好的方法来做到这一点,只要它不是过于复杂并且涉及安装外部应用程序,例如我见过的类似问题的一些解决方案(因为我只是初学者并试图学习)。 Thanks!谢谢!

Paremeter n in the sortTable function is the number of the row. Paremeter nsortTable功能是行的数量。 And when you render header of your table, you always pass 1. To fix it you can try当你渲染表格的标题时,你总是通过 1。要修复它,你可以尝试

{% for key in dict_table[0] %}
  <th onclick="sortTable({{ loop.index0 }})" style="cursor:crosshair">{{ key }}</th>
{% endfor %}

That should do the trick.这应该够了吧。

For further information visit this jinja tricks page and the full jinja documentation .有关更多信息,请访问此jinja 技巧页面和完整的jinja 文档

UPD Also there is a list of control structures . UPD还有一个控制结构列表。

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

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