Learning Flask: Part 3: Templates

Learning Flask

Flask is a microframework for server-side web development in Python.


Templates

Flask uses the template engine Jinja2 internally. This allows for Flask to respond to routes with template files.

Template functionality works through using two curly brackets to open and two to close for variable interpolation (expressions). Jinja2 also supports multiple types of usages.

  • {% ... %}Statements
  • {{ ... }}: Expressions
  • {# ... #}: Comments
  • #  ... ##: Line Statements

Note: Consult the Jinja2 guide for more details.

render_template()

Through working with Jinja2, Flask uses the render_template() function to select a specific file and add variables to be rendered along with it.

The first parameter to the render_template() is the file (in a folder labelled “templates” in the root directory) and the second is any variables (in a Dictionary) to be sent along.

The render_template() function returns the contents of the file given to it as filtered through its rendering system. This can be extremely useful when combined with Jinja2’s templates to build out from a ‘base’ to its children files.

Play with the example on Repl.it!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.