5 Templates| Flask开发

Templates are files that contain static data as well as placeholders for dynamic data. Flask uses the Jinja template library to render templates.

Jinja looks and behaves mostly like Python. Special delimiters are used to distinguish Jinja syntax from the static data in the template. Anything between {{ and }} is an expression that will be output to the final document. {% and %} denotes a control flow statement like if and for.

The Base Layout

flaskr/templates/base.html


<!-- title used to >
<title>{% block title %}{% endblock %} - Flaskrtitle>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
<nav>
  <h1>Flaskrh1>
  <ul>
    {% if g.user %}
      <li><span>{{ g.user['username'] }}span>
      <li><a href="{{ url_for('auth.logout') }}">Log Outa>
    {% else %}
      <li><a href="{{ url_for('auth.register') }}">Registera>
      <li><a href="{{ url_for('auth.login') }}">Log Ina>
    {% endif %}
  ul>
nav>
<section class="content">
  <header>
    {% block header %}{% endblock %}
  header>
  {% for message in get_flashed_messages() %}
    <div class="flash">{{ message }}div>
  {% endfor %}
  {% block content %}{% endblock %}
section>

g is automatically available in templates. There are three blocks defined here that will be overridden in the other templates: title, header and content.

Where to Store

The base template is directly in the templates directory. To keep the others organized, the templates for a blueprint will be placed in a directory with the same name as the blueprint.

Register

flaskr/templates/auth/register.html

{% extends 'base.html' %}

{% block header %}
  <h1>{% block title %}Register{% endblock %}h1>
{% endblock %}

{% block content %}
  <form method="post">
    <label for="username">Usernamelabel>
    <input name="username" id="username" required>
    <label for="password">Passwordlabel>
    <input type="password" name="password" id="password" required>
    <input type="submit" value="Register">
  form>
{% endblock %}

A Useful Pattern

A useful pattern used here is to place {% block title %} inside {% block header %}. This will set the title block and then output the value of it into the header block, so that both the window and page share the same title without writing it twice.

Required Attribute

The input tags are using the required attribute here. This tells the browser not to submit the form until those fields are filled in.

Log In

flaskr/templates/auth/login.html

{% extends 'base.html' %}

{% block header %}
  <h1>{% block title %}Log In{% endblock %}h1>
{% endblock %}

{% block content %}
  <form method="post">
    <label for="username">Usernamelabel>
    <input name="username" id="username" required>
    <label for="password">Passwordlabel>
    <input type="password" name="password" id="password" required>
    <input type="submit" value="Log In">
  form>
{% endblock %}

你可能感兴趣的:(web应用开发)