【问题标题】:Flask HTML template w/ Javascript带有 Javascript 的 Flask HTML 模板
【发布时间】:2014-10-07 14:08:55
【问题描述】:

我正在学习flask,并尝试构建一个在表格中显示财富500强公司数据的页面。

我已经让它正确显示,现在我尝试能够按任何列对表格进行排序。看起来我需要一些已存储在静态目录中的 Javascript,但我不太清楚如何将 javascript 拉入。

问题:

  • 我有正确的框架吗?
  • 如何正确利用 javascript?
  • 我读到我应该将任何脚本标签放在 base.html 中的头部,有没有时候我不会这样做?
  • 我不应该问哪些问题?

下面是我的文件结构

-app
 --static
   *sorttable.js
 --templates
   *base.html
   *companies.html
 --run.py
 --views.py
 --companies.csv

下面是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>

下面是company.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 %}

然后运行.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)

【问题讨论】:

    标签: javascript html python-2.7 flask


    【解决方案1】:

    我找到了如何让列表排序的答案

    我将 base.html 中的行从:

    <script> src="{{ url_for('static', filename='sorttable.js', type='text/javascript') }}"</script>
    

    <script src="{{ config.STATIC_URL }}/static/sorttable.js"></script>
    

    这似乎成功了。

    我当然很想从其他人那里得到关于如何总体改进的反馈

    【讨论】:

      【解决方案2】:

      您的script 标签不正确。不要在script (&lt;script&gt;) 之后立即关闭标签,您需要先包含其属性。

      <script src="{{ url_for('static', filename='sorttable.js') }}"></script>
      

      如果您使用 HTML5 (&lt;!doctype html&gt;),type="text/javascript" 是可选的,否则应包含在内。

      【讨论】:

        猜你喜欢
        • 2016-04-10
        • 2013-08-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-28
        • 2017-12-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多