06- template

More than just a template html file

Using a template file

  1. Create a directory under the project template folder templates
  2. Configuration template directory, in setting.py  which has a TEMPLATES item DIRS
'DIRS': [os.path.join(BASE_DIR,'templates')],  # 配置模板目录,默认是[],里面是空的 BASE_DIR:获取项目的绝对路径,与templates进行拼接 
  1. Create html file: Create a html file in the templates
  2. Use template files
    4.1 load the template file: Get down to the template directory contents html files, get a template object
    4.2 custom template context: data entry template file transfer
    4.3 rendering template: get a standard html content
def index(request):
    # return  HttpResponse("hello django")
    # 使用模板文件  # 1.加载模板文件,返回的是模板对象 temp = loader.get_template('booktest/index.html')  # 2.定义模板上下文:给模板文件传递数据 context=RequestContext(request,{}) context={}  # 3.模板渲染 res_html=temp.render(context)  # 4.返回给浏览器 return HttpResponse(res_html) 

The above method is not flexible enough, if there is a page, write it again, again, a function of their own package

def my_render(request,template_path,context_dict):

    temp = loader.get_template(template_path) # context=RequestContext(request,context_dict) context=context_dict res_html=temp.render(context) return HttpResponse(res_html) def index(request): return my_render(request,'booktest/index.html',{}) 

Template parameter

views.py:
return my_render(request,'booktest/index.html',{'now':now,'list':list(range(1,10))})

index.html:
<!DOCTYPE html>
<html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h>您好,这是一个模板文件</h><br/> now变量:<br/>{{now}}<br/> 遍历变量:<br/> <ul> {% for i in list%} <li>{{i}}</li> {% endfor %} </ul> </body> </html> 

Variable write {{}} template variable names, the snippet written in {}%%

Guess you like

Origin www.cnblogs.com/wysk/p/11295713.html