flask学习2

模版变量


from flask import Flask, render_template
app = Flask(__name__)

@app.route('/')
def index():
	user='valentine'
	return render_template('index.html',username=user)

	

if __name__ == '__main__':
	app.debug = True
	app.run()

 在index.py同级目录建立templates文件夹,下新建index.html




	index


	

Welcome, {{username}}!

 {{变量}},将变量传递给html。

模版标签


 

#coding:utf-8
from flask import Flask, render_template
app = Flask(__name__)

@app.route('/')
def index():
	user='valentine'
	nav_list=[u'首页',u'经济',u'文化',u'科技',u'娱乐']
	return render_template('index.html',username=user,nav_list=nav_list)

	

if __name__ == '__main__':
	app.debug = True
	app.run()

 传入nav_list参数,因为python不支持ascii码,所以在第一行加上。




	index


	

Welcome, {{username}}!

{%for nav in nav_list%}
  • {{nav}}
  • {%endfor%}

    for循环

    字典格式数据的遍历

    #coding:utf-8
    from flask import Flask, render_template
    app = Flask(__name__)
    
    @app.route('/')
    def index():
    	dic={'title':'blog','author':'valentine','date':'2015:06:25'}
    	return render_template('index.html',dic=dic)
    
    	
    
    if __name__ == '__main__':
    	app.debug = True
    	app.run()
    

    html:

    
    
    
    	index
    
    
    	
    {{dic['title']}}
    {%for item in dic%}
  • {{item}}
  • {%endfor%}

    第一行根据字典的key输出value,循环会取得字典的key,取value应该:

    {%for item in dic.values()%}
    

    两者同时取,应该:

    {%for key,value in dic.items()%}
    

    访问静态资源,如js,img,css

    #coding:utf-8
    from flask import Flask, render_template, url_for
    app = Flask(__name__)
    
    @app.route('/')
    def index():
    	img = url_for('static', filename='imgs/1.jpg')
    	return render_template('index.html',img=img)
    
    	
    
    if __name__ == '__main__':
    	app.debug = True
    	app.run()
    

    在同级目录建立static文件夹,下面存放静态资源。

     模版继承


     

    
      
            myBlog
      
      
        
    Microblog: Home

    {% block content %}{% endblock %}

    以上为base.html,同级目录index.html继承此模版:

    {% extends 'base.html' %}
    {% block content %}
    ....content
    {% endblock %}

    转载于:https://www.cnblogs.com/valentineisme/p/4280008.html

    你可能感兴趣的:(flask学习2)