Flask Template I - Jinga2

pwd

#you should here
/home/pyenv/versions/2.7.13/envs/flask_test

mkdir templates

example1:

vi templates/hello.html

<!doctype html>
<html>
   <body>

      <h1>Hello,{{ name }}!</h1>

   </body>
</html>
vi hello.py
from flask import Flask, render_template
ap = Flask(__name__)

@ap.route('/<who>')
def hello(who):
   return render_template('hello.html', name=who)

if __name__ == '__main__':
   ap.run(host = '0.0.0.0')
python hello.py

example2:

vi templates/allpeople.html
<!doctype html>
<html>
  <body>
    <table border = 1>
        {% for key, value in people.iteritems() %}
        
            <tr>
               <th> {{ key }} </th>
               <td> {{ value }} </td>
            </tr>
           
        {% endfor %}
    </table>
  </body>
</html>
vi allpeople.py
from flask import Flask, render_template
ap = Flask(__name__)

@ap.route('/allpeople')
def result():
   dict = {'phoebe':1,'range':2}
   return render_template('allpeople.html', people = dict)

if __name__ == '__main__':
   ap.run(host = '0.0.0.0')

python allpeople.py

#now, let's modify our previous example at Http mothods

cp login.html templates/
cp login.py login1.py


vi hello1.py

#must remember import render_template from flask
#add below into file under @app.route('/login', methods = ['POST', 'GET'])
@app.route('/')
def who():
    return render_template('login.html')
python hello1.py

#open browser with http://<ip/url>:5000


===


Jinga2 delimiters:


1.{{ Expressions to print to the template output }}

  variable、python basic type、op expression、filter(|)&tester(is)、string connector(~)、inline express(if)
  Escaping(ignore templates syntax): {{ '{{' }}

2.{% Statements %}
  2.1.
    {% if ... %}
      ...
    {% elif ... %}
      ...
    {% else %}
      ...
    {% endif %}

  2.2.
    {% for ... %}
      ...
    (% endfor %)

  2.3.
Escaping(ignore templates syntax)
    {% raw %}
      ...
    {% endraw %}

  2.4.
Escaping(ignore html syntax)
    {% autoescape false %}
      ...
    {% endautoescape $}


  2.5.assignment
    {% set <var> = <value> %}

  space control: {%+ %}、{% -%}、{%- -%}


3.# Statements
  # for ...
    ...
  # endfor

4.Comments not included in the template output
  4.1.
    {# ...
      ...
    #}

  4.2.
    ## comment

Template Designer Documentation:
http://jinja.pocoo.org/docs/2.10/templates/




Leave comments

authimage

Copyright(c) 2017 - PythonBlogs.com
By using this website, you signify your acceptance of Terms and Conditions and Privacy Policy
All rights reserved