flask-jinja2

flask-jinja2


  • 模板渲染
  • jinja2的模板渲染和大多数模板引擎一样,flask使用的是render_template方法, 第一个参数为模板的路径,后面的不定长参数为模板的模板参数
  •  1 from flask import Flask, render_template
     2 
     3 app = Flask(__name__, template_folder='templates', static_folder='static')
     4 
     5 
     6 @app.route('/')
     7 def index():
     8     return render_template('index.html')
     9 
    10 
    11 if __name__ == '__main__':
    12     app.run()

    在创建app时,可以对模板路径和静态文件的路径进行制定,不指定则采用默认值。 

  • 模板传参
  •  1 from flask import Flask, render_template
     2 
     3 app = Flask(__name__, template_folder='templates', static_folder='static')
     4 
     5 
     6 @app.route('/')
     7 def index():
     8     context = {
     9         'name': 'ivy',
    10         'age': 23,
    11         'sex': 'male',
    12         'list': [1, 2, 3],
    13         'dict': {'key': 'value'},
    14         'bool': True
    15     }
    16     return render_template('index.html', **context)
    17 
    18 
    19 if __name__ == '__main__':
    20     app.run()

    渲染的规则和Django大致一致

  • 具体渲染规则如下

猜你喜欢

转载自www.cnblogs.com/ivy-blogs/p/11503660.html