I'm learning flask and trying to build a page that displays data of the fortune 500 companies in a table.
I've gotten that to display correctly and am now trying to be able to sort the table by any of the columns. It looks like I need some Javascript which I've stored in my static directory but I'm not quite clear on how to pull the javascript in.
Questions:
Below is my file structure
-app
--static
*sorttable.js
--templates
*base.html
*companies.html
--run.py
--views.py
--companies.csv
Below is base.html
<html>
<head>
<script> src="{{ url_for('static', filename='sorttable.js', type='text/javascript') }}"</script>
{% if title %}
<title>{{ title }} - microblog</title>
{% else %}
<title>Welcome to microblog</title>
{% endif %}
</head>
<body>
<div>Microblog: <a href="/index">Home</a></div>
<div>Login: <a href="/login">Here</a></div>
<hr />
{% block content %}{% endblock %}
</body>
</html>
Below is companies.html
{% extends "base.html" %}
{% block content %}
<table class="sortable">
<table>
<thead>
<tr>
<th> Revenues </th>
<th> Profits </th>
<th> Rank </th>
<th> Company </th>
</tr>
</thead>
{% for keys in companies %}
<tr>
<td> {{ keys.Revenues }} </td>
<td> {{ keys.Profits }} </td>
<td> {{ keys.Rank }} </td>
<td> {{ keys.Standard }} </td>
</tr>
{% endfor %}
<tfoot>
</tfoot>
</table>
{% endblock %}
And run.py
# encoding: utf-8
from flask import render_template
from app import app
from .forms import LoginForm
@app.route('/companies')
def companies():
import csv
with open('companies.csv','rU') as f:
companies = csv.DictReader(f)
return render_template("companies.html",
title='Home',
companies=companies)
I found the answer to how to get the lists to sort
I changed the line in base.html from:
<script> src="{{ url_for('static', filename='sorttable.js', type='text/javascript') }}"</script>
to
<script src="{{ config.STATIC_URL }}/static/sorttable.js"></script>
that seemed to do the trick.
I'd definitely love to get feedback from others on how this could be improved generally
Your script
tag is incorrect. Instead of closing the tag right after script
( <script>
), you need to include its attributes first.
<script src="{{ url_for('static', filename='sorttable.js') }}"></script>
type="text/javascript"
is optional if you are using HTML5 ( <!doctype html>
) but should be included otherwise.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.