【问题标题】:Flask knows class in main app but not in html templateFlask 知道主应用程序中的类,但不知道 html 模板中的类
【发布时间】:2021-10-28 01:45:41
【问题描述】:

我有一个使用自定义类水果的 Flask 应用程序:

from flask import Flask, flash, render_template, redirect, url_for, jsonify, send_from_directory, request, make_response, Response
from werkzeug.utils import secure_filename
from Fruit import Fruit
import time
import os
import sys
from io import StringIO
from z3 import *
import jsonpickle
import traceback 
UPLOAD_FOLDER = './uploads'


sysn=sys.version_info.major

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER


@app.route("/")
def flask():
    return render_template('index.html', reload=time.time())

if __name__ == '__main__':
    print(f"Hurra simple working {str(Fruit)}")
    app.run(host='0.0.0.0')

它按预期在 main 中打印 Fruit 表示,但试图在 index.html 中显示它 像这样:

<h1>{{str(Fruit)}}</h1>

产生未定义的 NameError Fruit。它甚至告诉我标准的 Python 函数 str 没有定义。我可以做些什么来纠正这个问题?

【问题讨论】:

  • 我认为你需要在render_template('index.html', reload=time.time(), Fruit=Fruit)中传递Fruit

标签: python html flask jinja2


【解决方案1】:

如果你想在 HTML 文件中使用变量的值,你必须像这样传递它。

@app.route("/")
def flask():
    return render_template('index.html', reload=time.time(), Fruit = Fruit)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-04
    • 1970-01-01
    • 2021-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-24
    • 2014-12-19
    相关资源
    最近更新 更多