Flask02-Template

## 基础使用

    $ vim app/templates/index.html
    > 
    >   <head>
    >     {{title}} - microblog
    >   head>
    >   
    >       

Hello, {{user.nickname}}!

> > $ vim 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) ## 模板中控制语句( if-else for ) $ vim app/templates/index.html > > <head> > {% if title %} > {{title}} - microblog > {% else %} > microblog > {% endif %} > head> > >

Hi, {{user.nickname}}!

> {% for post in posts %} >

{{post.author.nickname}} says: {{post.body}}

> {% endfor %} > > $ vim app/views.py > def index(): > user = { 'nickname': 'Miguel' } # fake user > posts = [ # fake array of posts > { > 'author': { 'nickname': 'John' }, > 'body': 'Beautiful day in Portland!' > }, > { > 'author': { 'nickname': 'Susan' }, > 'body': 'The Avengers movie was so cool!' > } > ] > return render_template("index.html", > title = 'Home', > user = user, > posts = posts) ## 模板继承 $ vim app/templates/base.html <head> {% if title %} {{title}} - microblog {% else %} microblog {% endif %} head>
Microblog: "/index">Home

{% block content %}{% endblock %} $ vim app/templates/index.html {% extends "base.html" %} {% block content %}

Hi, {{user.nickname}}!

{% for post in posts %}

{{post.author.nickname}} says: {{post.body}}

{% endfor %} {% endblock %}

 

你可能感兴趣的:(Flask02-Template)