anon_swe
anon_swe

Reputation: 9335

Basic Flask: Using Helper Function w/in View

I'm following Miguel Grinberg's Flask tutorial here:

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

I'm trying to add a helper function and, based on the response here:

http://stackoverflow.com/questions/30677420/basic-flask-adding-helpful-functions

should be able to define a helper function within my views file and make use of it. For example, my app/views.py is currently:

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)

My app/templates/index.html file is currently:

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

However, when I run the local server, it renders as "hey everyone!" and that's it. My {{ user.nickname }} doesn't seem to get picked up.

I took out the {{ user.saying }} part and re-started the local server. It still says "hey everyone!" so clearly it's not updating based on the content I put in. Any idea why this might be happening?

Thanks, bclayman

Upvotes: 0

Views: 1311

Answers (2)

Chris
Chris

Reputation: 496

It's because the function index() never gets routed to. Remove the hey() function.

@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 apply to the following function. So try just moving the decorators above the function they should route to, like this:

from flask import render_template
from app import app

def hey():   
    return 'hey everyone!'

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

Upvotes: 1

JDrost1818
JDrost1818

Reputation: 1126

This worked for me:

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

EDIT: Oh do this:

def hey():   # <-- this function was being called not index()
    return 'hey everyone!'

@app.route("/")
@app.route("/index")
def index(): # <-- this function will now be called b/c it is directly under routes
    user = {'nickname': 'Ben', 'saying': hey()}
    return render_template('layout.html', title='Home', user=user)

if __name__ == '__main__':
    app.run(debug=True)

Upvotes: 1

Related Questions