HTML模块访问视图.py函数的属性

2024-06-08 11:13:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我现在正在创建一个仪表板,其中基于数据库中的表名创建一个导航栏(这部分没问题)。你知道吗

在视图.py我已经(编辑:添加了视图.py)地址:

    from flask import render_template
from app import app

import sqlite3, json

@app.route('/')
@app.route('/index')
def index():
    return render_template('index.html',title='Homepage',)
def nav_bar():
    connection = sqlite3.connect('C:\\SQLite\\Databases\\testPython.db')
    cursor = connection.cursor()

    cursor.execute('SELECT NAME FROM sqlite_master WHERE TYPE = \'table\';')
        #ORDER BY NAME ASC
        #tableNames = cursor.fetchall()

    connection.close()

    tableNames = json.dumps(cursor.fetchall()).replace("\"], [\"", " ").replace("[[\"","").replace("\"]]","").replace("access_","").split()

    return tableNames

我已经在中创建了导航导航.html如果代码是-

{% for names in navBar.tableNames %}
    <h1>Test</h1>
{% endfor %}

编辑:以下是基本.html你知道吗

<html>
    <head>
        <title>{{ title }} - Dashboard</title>
  </head>
  <body style="margin: 0; padding: 0;">
        <div style="height:7%; background-color: #171819;"><a href="/" style="color: white; vertical-align: middle; text-decoration: none; font-family: Sans-serif; font-size: 20px; position: relative; transform: translateY(-50%); top: 35%; padding-left: 5%">Access Log Dashboard >>></a></div>
        <div class="container">
          <div class="column-left" style="float: left; width: 15%; background-color: #3c3f42; height: 93%">
            {% include 'navigation.html' %}
          </div>
          <div class="column-centre" style="display: inline-block; width: 80%; color: #3c3f42;">
            {% block content %}
            {% endblock %}
          </div>
        </div>
  </body>
</html>

如何访问中的属性视图.py从导航.html?抱歉,如果这是一个新问题,我想是的!你知道吗


Tags: pyimportdiv视图appindextitlestyle
1条回答
网友
1楼 · 发布于 2024-06-08 11:13:43

首先,您需要将nav\u bar函数返回的表名传递给渲染模板,如下所示:

from flask import render_template
from app import app

import sqlite3, json

@app.route('/')
@app.route('/index')
def index():
    table_names = nav_bar()
    return render_template('base.html',title='Homepage',table_names = table_name)
def nav_bar():
    connection = sqlite3.connect('C:\\SQLite\\Databases\\testPython.db')
    cursor = connection.cursor()

    cursor.execute('SELECT NAME FROM sqlite_master WHERE TYPE = \'table\';')
        #ORDER BY NAME ASC
        #tableNames = cursor.fetchall()

    connection.close()

    table_names = json.dumps(cursor.fetchall()).replace("\"], [\"", " ").replace("[[\"","").replace("\"]]","").replace("access_","").split()

    return table_names

然后像这样调用模板:

{% for names in table_names %}
    <h1>names</h1>
{% endfor %}

相关问题 更多 >