Django中的模板知识点总结-动态部分

1、什么是Django模板

        Django中内置了自己的模板系统,称为DTL(Django Template Language),Django模板语言。Django模板带有DTL语言的HTML文件,该文件可被Django编译,可以传递参数,实现数据动态变化,最终返回给客户端。

        DTL中的语法涉及四个部分:

                注释:注释;

                变量:变量在模板被执行时将被替换为实际值 -- {{ ... }} ;

                标签:用于控制模板逻辑 {% ... %}  ;

                过滤器:用于转换变量或标签的值。

2、相关配置

在setting.py中

TEMPLATES = [
   {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        # 指定模板文件存储的位置
        'DIRS': [ BASE_DIR , 'templates'],
        # 自动搜索应用目录
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
           ],
       },
  },
]

        Django中有多个应用时,应优先在根目录templates中找,再到应用目录下找,不要重名。

3、渲染模板

        在Django的模板系统中,可通过render()函数来完成渲染模板的功能。 其语法结构是:

from django.shortcuts import render
render(request,template_name,content=None,content_type=None,status=None)

request代表用于生成此响应的请求对象

template_name代表要渲染的模板文件的名称,一般放在templates目录下,需要自行创建

content代表要传递到模板的数据形成的数据字典

content_type代表模板文件的MIME类型,默认为text/html

status代表响应的状态码,默认为200

render()函数返回HttpResponse对象,是更加简洁的输出。

#显示界面,此仅仅是返回了一个界面,该界面在templates目录下,没有传递参数
def index(request):
    return render(request,'index.html')
#有传递参数
def variable(request):
    username = 'Tom'
    age = 23
    sex = True
    score = {
        'chinese':128,
        'math':149,
        'english':122
    }
    friends = ['John','Rose','Frank','Ben']
    return render(request,'variable.html',locals())

        视图函数variable(),通过locals()方法,以字典的方式,传递了视图函数中的所有变量,也可以单独设置一个字典来传递参数,如下说是:

#有传递参数
def variable(request):
    username = 'Tom'
    age = 23
    sex = True
    score = {
        'chinese':128,
        'math':149,
        'english':122
    }
    friends = ['John','Rose','Frank','Ben']
    return render(request,'variable.html',{"username":username,"age":age,"sex":sex,"score":score,"friends":friends})

或者:

#有传递参数
def variable(request):
    username = 'Tom'
    age = 23
    sex = True
    score = {
        'chinese':128,
        'math':149,
        'english':122
    }
    friends = ['John','Rose','Frank','Ben']
    context = {
        "username":username,
        "age":age,
        "sex":sex,
        "score":score,
        "friends":friends
    }
    return render(request,'variable.html',context)

4、模板变量

        模板变量,除了可以是字符串外,还可以是列表、字典和类对象。DTL中的变量通过双花括号进行访问:

{{ variable}}
{{ variable.key }}
{{ variable.index }}
{{ variable.property }}

例子如下,view.py中的代码:

def variable(request):
    username = 'Tom'
    age = 23
    sex = True
    score = {
        'chinese':128,
        'math':149,
        'english':122
    }
    friends = ['John','Rose','Frank','Ben']
    return render(request,'variable.html',locals())

variable.html中的代码如下:

<body>
  <h1>Variable</h1>
  <p>username:{{ username }}</p>
  <p>age:{{ age }}</p>
  <p>sex:{{ sex }}</p>
  <p>chinese:{{ score.chinese }}</p>
  <p>math:{{ score.math }}</p>
  <p>english:{{ score.english }}</p>
  <p>{{ friends.0 }},{{ friends.1 }},{{ friends.2 }},{{ friends.3 }}</p>
  {% include 'inc/footer.html'%}
</body>

别忘了在url.py中添加路由:

    path('variable/',views.variable),

5、标签

5.1、for标签

{% for iterate_value in sequence %}
...
...
{% endfor %}
{% for iterate_value in sequence %}
...
...
{% empty%}
  ...
  ...
{% endfor %}
例子如下:
<table width="900" cellpadding="10" celspacing="0" border="1">
      <tr>
          <td>id</td>
          <td>name</td>
      </tr>
      {% for item in lists %}
      <tr>
          <td>{{ item.id }}</td>
          <td>{{ item.name }}</td>
      </tr>
      {% empty %}
      <tr>
        <td colspan="2">对不起,列表为空</td>
      </tr>
      {% endfor %}
 </table>

5.2、for循环中的内置变量

变量描述
forloop.counter 循环记数器,从1开始
forloop.counter0 循环记数器,从0开始
forloop.revcounter 反向循环记数器,最后一个为1
forloop.revcounter0 反向循环记数器,最后一个为0
forloop.first 当前循环为第一个时,该变量值为True
forloop.last 当前循环为最后一个时,该变量值为True
示例如下,views.py中的代码:
def forloop(request):
    books = [
        {
            'id':5,
            'bookname': '孙子兵法大全集(超值金版)',
            'price': 18.4,
            'publishing': '新世界出版社',
            'category': '历史'
        },
        {
            'id': 11,
            'bookname': '甲骨文丛书·拿破仑大帝(全2册) ',
            'price': 119.5,
            'publishing': '中信出版集团',
            'category': '传记'
        },
        {
            'id': 22,
            'bookname': 'JavaScript DOM编程艺术(第2版)',
            'price': 42.70,
            'publishing': '人民邮电出版社',
            'category': '计算机'
        },
        {
            'id': 23,
            'bookname': '精通iOS开发 第8版',
            'price': 102.20,
            'publishing': '人民邮电出版社',
            'category': '计算机'
        },
        {
            'id': 26,
            'bookname': 'UNIX网络编程 卷1 套接字联网API(第3版)',
            'price': 102.9,
            'publishing': '人民邮电出版社',
            'category': '计算机'
        },
        {
            'id': 31,
            'bookname': '曾国藩的正面与侧面:1+2(套装共两册)',
            'price': 59.30,
            'publishing': '岳麓书社',
            'category': '传记'
        },
        {
            'id': 40,
            'bookname': '普京传:不可替代的俄罗斯硬汉 [Mr.Putin: Operative In The Kremlin]  ',
            'price': 39,
            'publishing': '红旗出版社',
            'category': '传记'
        },
    ]


    # lists = [
    #     {'id':5,'name':'Rose'},
    #     {'id': 7, 'name': 'Frank'},
    # ]
    lists = []
    context = {
        'books':books,
        'lists':lists
    }
    return render(request,'forloop.html',context)
forloop.html 的代码如下:
<table width="900" cellpadding="10" celspacing="0" border="1">
      <tr>
          <td>序号</td>
          <td>书名</td>
          <td>价格</td>
          <td>出版社</td>
          <td>分类</td>
          <td>操作</td>
      </tr>
      {% for book in books %}
      <tr class="{% cycle 'primary' 'second' %}">
          <td>{{ forloop.counter }}</td>
          <td>{{ book.bookname }}</td>
          <td>{{ book.price }}</td>
          <td>{{ book.publishing }}</td>
          <td>{{ book.category }}</td>
          <td>
              <a href="/book/get/{{ book.id }}">修改</a>
              &nbsp;&nbsp;
              <a href="/book/delete/{{ book.id }}">删除</a>
          </td>
      </tr>
      {% endfor %}
  </table>

还有urls.py中的路由:path('forloop/',views.forloop),

5.3、cycle循环结构

        在每次遇到cycle 标记时,都会产生一个参数。第一次产生第一个参数,第二次产生第二个参数,依次类推。一旦用尽所有参数,再次循环时则产生第一个参数。其语法结构是:
{% cycle 'value1' 'value2' 'value3' '...'%}

5.4、if结构

{% if condition %}
  ...
{% endif %}
或者
{% if condition %}
  ...
{% else %}
  ...
{% endif %}
或者
{% if condition %}
  ...
{% elif condition %}
  ...
{% elif condition %}
  ...
{% else %}
  ...
{% endif %}
5.5、templatetag结构
        该语法结构是为了显示一个特殊转移字符串,基本语法结构: {% templatetag templatebit%}
模板位说明
openblock {%
closeblock %}
openvariable {{
closevariable }}
opencomment {#
closecomment #}

5.5、verbatim结构

        verbatim标签用于告诉 DTL 停止渲染此标签内的内容,其语法是:
{% verbatim%}
  ...
{% endverbatim %}

5.6、url语法

        url标签用于近回与指定路由和可选参数相匹配的绝对路径引用 ( 不包括域
名) ,其格式为:{% url 'route_name' arg1 arg2 .. %}
<p><a href="{% url 'deletebook' id=5 %}">删除5号图书</a></p>

5.7、 include

        include标签用于在一个模板文件中包含另外一个模板文件,其语法结构
是: {% include 'filename' %}
        在需要模板插入的地方,写入如下代码:
{% include 'inc/footer.html'%}

在inc文件夹下的footer.html中的全部代码如下:

<div style="text-align:center;font-size:14px;line-height:2em;">
    <p>&copy;达内教育版权所有 2002~2023</p>
    <p>通讯地址:北京市中关村中鼎大厦7层</p>
    <p>联系电话:010-123456789</p>
</div>

5.8 、csrf_token

        csrf_token称为令牌标签,其作用是为了防止跨域请求伪造,其原理是表单内添加一个隐藏域,其值为加密信息,在表单 POST提交时将与服务器产生的加密信息进行匹配,匹配成功则意味合法用户。 语法如下:{% csrf_token %}
示例如下:
<form action="" method="post">
    {% csrf_token %}
    <table width="800" align="center" border="1" cellpadding="10" cellspacing="0">
        <tr>
            <td>用户名</td>
            <td><input type="text" name="username"></td>
        </tr>
        <tr>
            <td>密码</td>
            <td><input type="password" name="password"></td>
        </tr>
        <tr>
            <td>确认密码</td>
            <td><input type="password" name="password2"></td>
        </tr>
        <tr>
            <td colspan="2"><input type="submit" value="提交"></td>
        </tr>
    </table>
</form>

6、过滤器

过滤器用于转换变量或标签参数的值,其语法结构是:

6.1、safe

safe 用于标记一个字符串在输出前不需要对 HTML 标记进行转义,语法结
构是:{{ value | filter}}

6.2、truncatechars

用于完成字符串的截取,其语法结构是:

6.3、yesno

True , False None ( 可选 ) 值映射到以英文逗号分隔的数据,其结构为:
{{ value | safe }}
{{ value | truncatechars: 长度 }}
{{ value | yesno:"True 时的值 ,False 时的值 ,None 时的值 "}}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值