Flask: Difference between revisions
Jump to navigation
Jump to search
Line 23: | Line 23: | ||
So flask like others such pug or egs has templates. Very similar indeed | So flask like others such pug or egs has templates. Very similar indeed | ||
<syntaxhighlight lang="py"> | <syntaxhighlight lang="py"> | ||
@app.route('/') | @app.route('/') | ||
@app.route('/index') | @app.route('/index') | ||
def index(): | def index(): | ||
user = {'username': ' | user = {'username': 'Miguel'} | ||
return render_template('index.html', title='Home', user=user) | posts = [ | ||
{ | |||
'author': {'username': 'John'}, | |||
'body': 'Beautiful day in Portland!' | |||
}, | |||
{ | |||
'author': {'username': 'Susan'}, | |||
'body': 'The Avengers movie was so cool!' | |||
} | |||
] | |||
return render_template('index.html', title='Home', user=user, posts=posts) | |||
</syntaxhighlight> | </syntaxhighlight> | ||
And the template | And the template | ||
Line 36: | Line 43: | ||
<html> | <html> | ||
<head> | <head> | ||
<title>{{ title }} - | {% if title %} | ||
<title>{{ title }} - Microblog</title> | |||
{% else %} | |||
<title>Welcome to Microblog</title> | |||
{% endif %} | |||
</head> | </head> | ||
<body> | <body> | ||
<h1> | <h1>Hi, {{ user.username }}!</h1> | ||
{% for post in posts %} | |||
<div><p>{{ post.author.username }} says: <b>{{ post.body }}</b></p></div> | |||
{% endfor %} | |||
</body> | </body> | ||
</html> | </html> | ||
</syntaxhighlight> | </syntaxhighlight> |
Revision as of 04:33, 23 May 2021
Introduction
Quick tour of the python framework flask
Getting Started
from app import app
@app.route('/')
@app.route('/index')
def index():
user = {'username': 'Miguel'}
return '''
<html>
<head>
<title>Home Page - Microblog</title>
</head>
<body>
<h1>Hello, ''' + user['username'] + '''!</h1>
</body>
</html>'''
Routing
Templates
So flask like others such pug or egs has templates. Very similar indeed
@app.route('/')
@app.route('/index')
def index():
user = {'username': 'Miguel'}
posts = [
{
'author': {'username': 'John'},
'body': 'Beautiful day in Portland!'
},
{
'author': {'username': 'Susan'},
'body': 'The Avengers movie was so cool!'
}
]
return render_template('index.html', title='Home', user=user, posts=posts)
And the template
<html>
<head>
{% if title %}
<title>{{ title }} - Microblog</title>
{% else %}
<title>Welcome to Microblog</title>
{% endif %}
</head>
<body>
<h1>Hi, {{ user.username }}!</h1>
{% for post in posts %}
<div><p>{{ post.author.username }} says: <b>{{ post.body }}</b></p></div>
{% endfor %}
</body>
</html>