Skip to content
Myr

templates.rst

This file

Path

docs/tutorial/templates.rst

187 lines · 6.8 KiB

Last changed by

Not known.

History of this file

Take it

The walk stopped after 200 commits: lines older than bbb273b point at it.

Merge pull request #3828 from pallets/move-send-fileDavid Lordbefore adoptionbbb273b

lines 1–187why, one step back
1.. currentmodule:: flask
23Templates4=========56You've written the authentication views for your application, but if7you're running the server and try to go to any of the URLs, you'll see a8``TemplateNotFound`` error. That's because the views are calling9:func:`render_template`, but you haven't written the templates yet.10The template files will be stored in the ``templates`` directory inside11the ``flaskr`` package.1213Templates are files that contain static data as well as placeholders14for dynamic data. A template is rendered with specific data to produce a15final document. Flask uses the `Jinja`_ template library to render16templates.1718In your application, you will use templates to render `HTML`_ which19will display in the user's browser. In Flask, Jinja is configured to20*autoescape* any data that is rendered in HTML templates. This means21that it's safe to render user input; any characters they've entered that22could mess with the HTML, such as ``<`` and ``>`` will be *escaped* with23*safe* values that look the same in the browser but don't cause unwanted24effects.2526Jinja looks and behaves mostly like Python. Special delimiters are used27to distinguish Jinja syntax from the static data in the template.28Anything between ``{{`` and ``}}`` is an expression that will be output29to the final document. ``{%`` and ``%}`` denotes a control flow30statement like ``if`` and ``for``. Unlike Python, blocks are denoted31by start and end tags rather than indentation since static text within32a block could change indentation.3334.. _Jinja: https://jinja.palletsprojects.com/templates/35.. _HTML: https://developer.mozilla.org/docs/Web/HTML363738The Base Layout39---------------4041Each page in the application will have the same basic layout around a42different body. Instead of writing the entire HTML structure in each43template, each template will *extend* a base template and override44specific sections.4546.. code-block:: html+jinja47 :caption: ``flaskr/templates/base.html``4849 <!doctype html>50 <title>{% block title %}{% endblock %} - Flaskr</title>51 <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">52 <nav>53 <h1>Flaskr</h1>54 <ul>55 {% if g.user %}56 <li><span>{{ g.user['username'] }}</span>57 <li><a href="{{ url_for('auth.logout') }}">Log Out</a>58 {% else %}59 <li><a href="{{ url_for('auth.register') }}">Register</a>60 <li><a href="{{ url_for('auth.login') }}">Log In</a>61 {% endif %}62 </ul>63 </nav>64 <section class="content">65 <header>66 {% block header %}{% endblock %}67 </header>68 {% for message in get_flashed_messages() %}69 <div class="flash">{{ message }}</div>70 {% endfor %}71 {% block content %}{% endblock %}72 </section>7374:data:`g` is automatically available in templates. Based on if75``g.user`` is set (from ``load_logged_in_user``), either the username76and a log out link are displayed, or links to register and log in77are displayed. :func:`url_for` is also automatically available, and is78used to generate URLs to views instead of writing them out manually.7980After the page title, and before the content, the template loops over81each message returned by :func:`get_flashed_messages`. You used82:func:`flash` in the views to show error messages, and this is the code83that will display them.8485There are three blocks defined here that will be overridden in the other86templates:8788#. ``{% block title %}`` will change the title displayed in the89 browser's tab and window title.9091#. ``{% block header %}`` is similar to ``title`` but will change the92 title displayed on the page.9394#. ``{% block content %}`` is where the content of each page goes, such95 as the login form or a blog post.9697The base template is directly in the ``templates`` directory. To keep98the others organized, the templates for a blueprint will be placed in a99directory with the same name as the blueprint.100101102Register103--------104105.. code-block:: html+jinja106 :caption: ``flaskr/templates/auth/register.html``107108 {% extends 'base.html' %}109110 {% block header %}111 <h1>{% block title %}Register{% endblock %}</h1>112 {% endblock %}113114 {% block content %}115 <form method="post">116 <label for="username">Username</label>117 <input name="username" id="username" required>118 <label for="password">Password</label>119 <input type="password" name="password" id="password" required>120 <input type="submit" value="Register">121 </form>122 {% endblock %}123124``{% extends 'base.html' %}`` tells Jinja that this template should125replace the blocks from the base template. All the rendered content must126appear inside ``{% block %}`` tags that override blocks from the base127template.128129A useful pattern used here is to place ``{% block title %}`` inside130``{% block header %}``. This will set the title block and then output131the value of it into the header block, so that both the window and page132share the same title without writing it twice.133134The ``input`` tags are using the ``required`` attribute here. This tells135the browser not to submit the form until those fields are filled in. If136the user is using an older browser that doesn't support that attribute,137or if they are using something besides a browser to make requests, you138still want to validate the data in the Flask view. It's important to139always fully validate the data on the server, even if the client does140some validation as well.141142143Log In144------145146This is identical to the register template except for the title and147submit button.148149.. code-block:: html+jinja150 :caption: ``flaskr/templates/auth/login.html``151152 {% extends 'base.html' %}153154 {% block header %}155 <h1>{% block title %}Log In{% endblock %}</h1>156 {% endblock %}157158 {% block content %}159 <form method="post">160 <label for="username">Username</label>161 <input name="username" id="username" required>162 <label for="password">Password</label>163 <input type="password" name="password" id="password" required>164 <input type="submit" value="Log In">165 </form>166 {% endblock %}167168169Register A User170---------------171172Now that the authentication templates are written, you can register a173user. Make sure the server is still running (``flask run`` if it's not),174then go to http://127.0.0.1:5000/auth/register.175176Try clicking the "Register" button without filling out the form and see177that the browser shows an error message. Try removing the ``required``178attributes from the ``register.html`` template and click "Register"179again. Instead of the browser showing an error, the page will reload and180the error from :func:`flash` in the view will be shown.181182Fill out a username and password and you'll be redirected to the login183page. Try entering an incorrect username, or the correct username and184incorrect password. If you log in you'll get an error because there's185no ``index`` view to redirect to yet.186187Continue to :doc:`static`.