Flask notes: 3: Templates

Source: Internet
Author: User

The current directory structure:MyBlog|----Flask|----TMP|----App|----static|----Templates|----__init__.py|----views.py|----run.py
writing the first templateapp/templates/index.html


{{....}} is a variable in{%....%} expressiondata is dynamically fetched from the view template
Modify a view template app/views.py
From flask import render_templatefrom app import App@app.route ('/') @app. Route ('/index ') def index ():    user={' Nickname ': ' Bob '}    return Render_template ("index.html",    title= "Home",    user=user) #从flask导入render_ Template#render_template (HTML file, variable to pass data)


the template's judgment statementModify App/templates/index.html


If you delete the title parameter in the Render_template () function in app/views.pythe title in the browser will become Welcome-myblog
looping statements for templatesModify app/views.py
From flask import render_templatefrom app import App@app.route ('/') @app. Route ('/index ') def index ():    user={' Nickname ': ' Bob '}    posts=[            {' author ': {' nickname ': ' John '},             ' body ': ' Beautiful day in Portland! '},            {' Author ': {' nickname ': ' Susan '},             ' body ': ' The Avengers movie is so cool! '}           ]    Return Render_template ("index.html",    title= "Home",    User=user,    posts=posts)


Modify App/templates/index.html


Display:

Template InheritanceA fixed branch of a template appears in many templates several times, and we can make templates individually and then inherit from the template we need
Add a navigation bar templateapp/templates/base.html


{%block content%}{%endblock%}between the two expressions is where the new template can be inserted
Modify App/templates/index.html
{% extends "base.html"%} {% block content%}


{%extends page%} This is an inheritance template{%block content%}{%endblock%}between the two expressions is where the content can be inserted
Display:

index.html more base.html content

Flask notes: 3: Templates

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.