Flask practice - microblog template (2)

template

  1. create app/templates/index.html
    <html>
      <head>
        <title>{{title}} - microblog</title>
      </head>
      <body>
          <h1>Hello, {{user.nickname}}!</h1>
      </body>
    </html>
  2. Modify app/views.py
    from flask import render_template
    from app import app
    
    @app.route('/')
    @app.route('/index')
    def index():
        user = { 'nickname': 'Miguel' } # fake user
        return render_template("index.html",
            title = 'Home',
            user = user)
  3. Control statements in templates, use {%…%} code blocks
    修改index.html
    <html>
      <head>
        {% if title %}
        <title>{{title}} - microblog</title>
        {% else %}
        <title>microblog</title>
        {% endif %}
      </head>
      <body>
        <h1>Hi, {{user.nickname}}!</h1>
        {% for post in posts %}
        <p>{{post.author.nickname}} says: <b>{{post.body}}</b></p>
        {% endfor %}
      </body>
    </html>
  4. Template inheritance
    uses block control statements to define where derived templates can be inserted, creating app/templates/base.html
    <html>
      <head>
        {% if title %}
        <title>{{title}} - microblog</title>
        {% else %}
        <title>microblog</title>
        {% endif %}
      </head>
      <body>
        <div>Microblog: <a href="/index">Home</a></div>
        <hr>
        {% block content %}{% endblock %}
      </body>
    </html>

    Modify index.html

    {% extends "base.html" %}
    {% block content %}
    <h1>Hi, {{user.nickname}}!</h1>
    {% for post in posts %}
    <div><p>{{post.author.nickname}} says: <b>{{post.body}}</b></p></div>
    {% endfor %}
    {% endblock %}

     

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324887410&siteId=291194637