zoukankan      html  css  js  c++  java
  • 06-模板

    模板不仅仅是一个html文件

    模板文件的使用

    1. 在项目目录下创建模板文件夹templates
    2. 配置模板目录,在setting.py 里面有一个TEMPLATES项DIRS
    'DIRS': [os.path.join(BASE_DIR,'templates')],  # 配置模板目录,默认是[],里面是空的
    
    BASE_DIR:获取项目的绝对路径,与templates进行拼接
    
    1. 创建html文件:在templates下创建html文件
    2. 使用模板文件
      4.1.加载模板文件:去模板目录下获取html文件的内容,得到一个模板对象
      4.2.定义模板上下文:项模板文件传递数据
      4.3.模板渲染:得到一个标准的html内容
    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)
    

    上面的方法不够灵活,如果还有页面,又要重新写一遍,自己封装一个函数

    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',{})
    

    模板参数传递

    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>
    

    变量写在{{模板变量名}}中,代码段写在{% %}中

  • 相关阅读:
    (转)const变量通过指针修改问题
    sleep wait yeild join
    做事贵在坚持
    我的学习进度
    织梦dedecms后台添加图片style全部都变成st<x>yle的解决办法
    调用DEDE日期时间格式整理大全
    Arcgis andoid开发之应用百度地图接口实现精准定位与显示
    jquery自定义插件——window的实现
    lzugis—搭建属于自己的小型的版本控制SVN
    lzugis——Arcgis Server for JavaScript API之自定义InfoWindow
  • 原文地址:https://www.cnblogs.com/wysk/p/11295713.html
Copyright © 2011-2022 走看看