Intro to Flask Part 2
Dynamic Routes
@app.route('/hello/<name>)
def hello(name):
return f'Hello {name}Returning HTML from Flask
You can either return HTML as a string like so:
@app.route('/hello')
def hello_world():
return """
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Hello there.</h1>
<p>Isn't this lovely!</p>
</body>
</html>
"""or use a template.
Serving Dynamic Templates & Static Files
Create static and templates directories so the project directory looks like so:
Rendering a Template
Flask will automatically look for template files in templates.
Flask uses the Jinja templating engine.
To render a Jinja template, first import the render_template function
Then instead of returning a string in the route handler, return the result of calling render_template('{templatename}.html').
app.py
templates/index.html
Adding a Stylesheet
Like templates, Flask will automatically look for and and serve static files in static. So you just have to create your stylesheet file and include it in the template.
Adding Images
Add any image in the static directory (preferably in the img directory but you do you) and flask will serve it at /static/PATH_TO_IMAGE.
Passing Data to Templates
app.py
templates/hello.html
Last updated
Was this helpful?