Wolf book chapter summary template Jinja2

I have to say this one gave me a great help and inspiration, so this is a good summary I would write, not just the contents of the book, more of my personal ideas and understanding

Firstly, all along app.py code into the code generation of ideas and knowledge

import os
from flask import Flask, render_template, flash, redirect, url_for, Markup

app = Flask(__name__)
app.secret_key = os.getenv('SECRET_KEY', 'secret string')
app.jinja_env.trim_blocks = True
app.jinja_env.lstrip_blocks = True

user = {
    'username': 'Grey Li',
    'bio': 'A boy who loves movies and music.',
}

movies = [
    {'name': 'My Neighbor Totoro', 'year': '1988'},
    {'name': 'Three Colours trilogy', 'year': '1993'},
    {'name': 'Forrest Gump', 'year': '1994'},
    {'name': 'Perfect Blue', 'year': '1997'},
    {'name': 'The Matrix', 'year': '1999'},
    {'name': 'Memento', 'year': '2000'},
    {'name': 'The Bucket list', 'year': '2007'},
    {'name': 'Black Swan', 'year': '2010'},
    {'name': 'Gone Girl', 'year': '2014'},
    {'name': 'CoCo', 'year': '2017'},
]


@app.route('/watchlist')
def watchlist():
    return render_template('watchlist.html', user=user, movies=movies)


@app.route('/')
def index():
    return render_template('index.html')


# register template context handler
#自定义上下文变量,返回值必须为字典
@app.context_processor
def inject_info():
    foo = 'I am foo.'
# custom global function
# Register function Global Template
    dict return (foo = foo) # equal to: {return 'foo': foo}


@app.template_global()
def bar():
    return 'I am bar.'


# register template filter
@app.template_filter()
def musical(s):
    return s + Markup(' ♫')


# register template test
@app.template_test()
def baz(n):
    if n == 'baz':
        return True
    return False


@app.route('/watchlist2')
def watchlist_with_static():
    return render_template('watchlist_with_static.html', user=user, movies=movies)


# message flashing
@app.route('/flash')
def just_flash():
    flash('I am flash, who is looking for me?')
    return redirect(url_for('index')) 


# 404 error trades
@app.errorhandler(404)
def page_not_found(e):
    return render_template('errors/404.html'), 404


# 500 error handler
@app.errorhandler(500)
def internal_server_error(e):
    return render_template('errors/500.html'), 500

app.run(debug=True)

 First, create an instance

The information the user list and movies all reached a new url, the new url in an html page to return to output this information

So here it created a new watchlist.html, the purpose is to return html url function corresponding to view incoming content

watchlist.html code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{user.username}}'s Watchlist</title>
</head>
<body>

<a href="{{ url_for('index') }}">← Return</a>
<h2>{{user.username}}</h2>

{% if user.bio %}
    <i>{{user.boio}}</i>
{% else %}
    <i>This user has not provided a bio.</i>
{% endif %}

<h5>{{ user.username }}'s Watchlist ({{movies | length}}):</h5>
<ul>
    {% for movie in movies %}
        <li>{{movie.name}} - {{movie.year}}</li>
    {% endfor%}
</ul>

</body>
</html>

There are two knowledge points, also commonly used in Jinja2 template syntax, for loops and if judgment

The only noteworthy thing is to start would correspond to the corresponding end

{% if xxx %} -----{% endif %}

{% for xxx %} ----{% endfor %}

Variables in the template, you need to import the view functions

The code flow then Analysis:

1. context variables:

Context variables may be used directly in the module, the module corresponding to the global variable.

Custom variable using context decorator @ app.context_processor

(1)@app.context_processor

def xxx():

  pass

(2) and of course by defining the function, then the function returns to the process in a manner

def xxx():

  pass

app.context_processor(xxx)

2. Global Functions: global function is the equivalent of all modules can be used.

Global function is the use of a custom decorator: @ app.template_global:

3. Filter: template tool, the operation target | filtration methods (e.g. watchlist.html {{movies | length}}) calculated how long the movies

4. tester: tester is used to determine from the literal meaning and Comparative Test

Key decorator @ app.templat_text (), as the following example is meant to baz function incoming parameters, comparison, and then to return the results according to Comparative

The base template: come at the soul of the Jinja2

Template-based meaning to popular understanding is shared block

The concept of a block template is divided into several blocks

<!DOCTYPE html>
<html>
<head>
    {% block head %}
        <meta charset="utf-8">
        <title>{% block title %}Template - HelloFlask{% endblock %}</title>
        <link rel="icon" type="image/x-icon" href="{{ url_for('static', filename='favicon.ico') }}">
        {% block styles %}
            <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css' ) }}">
        {% endblock %}
    {% endblock %}
</head>
<body>
<nav>
    <ul><li><a href="{{ url_for('index') }}">Home</a></li></ul>
</nav>

<main>
    {% for message in get_flashed_messages() %}
        <div class="alert">{{ message }}</div>
    {% endfor %}
    {% block content %}{% endblock %}
</main>
<footer>
    {% block footer %}
        <small> © 2018 <a href="http://greyli.com" title="Written by Grey Li">Grey Li</a> /
            <a href="https://github.com/greyli/helloflask" title="Fork me on GitHub">GitHub</a> /
            <a href="http://helloflask.com" title="A HelloFlask project">HelloFlask</a>
        </small>
    {% endblock %}
</footer>
{% block scripts %}{% endblock %}
</body>
</html>

 From the above analysis Code

{% Block head%} There are two blocks

Is a {% block title%} for captions

Another is {% block style%} for storing reading css link blocks each end, must use the corresponding {% endblcok%} keyword to an end block.

In the <body> tag in the first jump there is a small Home button to jump to the home page,

Then read <main> Tags flash message in the message, and stored for {% block content%} of information to facilitate sub-module inherits

Create {% block footer%} in the block <footer> tag, used to store footer information.

The last block is {% block script%} js script for placement block link

6. The sub-template inheritance

As long as the child is inherited template-based module, then began to use the template extend 'base template name'

And when the content or the content of the writing, the main module must have been defined in the operation block,

The {% block content%} xxx {% endblock%}, the contents of the middle sub-module is added.

7. Load static files (js.css.img)

Using the <link> tag to load a static file, {% block style%} loading css file, the file is loaded in js {% block scripts%}, as follows

8. Macro

9. macro loads the static files

10. Load Favion: page has a small icon

Link tag used directly in the module, and pay attention to the label file selection properties

 

Guess you like

Origin www.cnblogs.com/dachang/p/11189416.html