基本Flask:使用辅助函数w/in Vi

2024-04-29 02:05:28 发布

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

以下是米格尔·格林伯格的烧瓶教程:

http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-ii-templates

我尝试添加一个helper函数,根据这里的响应:

^{pr2}$

应该能够在我的视图文件中定义一个助手函数并利用它。例如,我的app/views.py当前是:

from flask import render_template
from app import app

@app.route("/")
@app.route("/index")
def hey():
    return 'hey everyone!'
def index():
    user = {'nickname': 'Ben', 'saying': hey()}
    return render_template('index.html', title='Home', user=user)

我的app/templates/index.html文件当前为:

<html>
    <head>
        <title>{{ title }} - microblog</title>
    </head>
    <body>
        <h1> {{ user.saying }}, {{ user.nickname }}!</h1>
    </body>
</html>

但是,当我运行本地服务器时,它呈现为"hey everyone!",仅此而已。我的{{ user.nickname }}似乎没有被接上。在

我取出{{ user.saying }}部分,重新启动本地服务器。它仍然写着"hey everyone!"所以很明显它不是根据我输入的内容进行更新的。知道为什么会这样吗?在

谢谢, B外行


Tags: 文件函数fromimportappflaskindextitle
2条回答

这对我很有效:

<html>
    <head>
        <title>{{ title }} - microblog</title>
    </head>
    <body>
        <h1> {{ user["saying"]}}, {{ user["nickname"]}}!</h1>
    </body>
</html>

编辑:哦,这样做:

^{pr2}$

这是因为函数index()从未被路由到。删除hey()函数。在

@app.route("/")
@app.route("/index")
def hey():   # <  the decorators (@app.route) only applies to this function
    return 'hey everyone!'
def index(): # <  this function never gets called, it has no decorators
    user = {'nickname': 'Ben', 'saying': hey()}
    return render_template('index.html', title='Home', user=user)

Decorators应用于以下函数。所以试着把装饰器移到它们应该路由到的函数上面,像这样:

^{pr2}$

相关问题 更多 >