zoukankan      html  css  js  c++  java
  • Python Django框架笔记(六):模板

    (一){%%}和{{ }}

    1 {% for post in posts %}
    2         <a href=""><h2>{{ post.title }}</h2></a>
    3         <p>{{ post.body }}</p>
    4         <p>{{ post.timestamp }}</p>
    5         <hr>
    6 {% endfor %}

    {%%}:里面的是模板标签,{{}}里面的是变量

    {%%}标签:

    1 {% if  x == 1%} 
    2      <p></p>
    3 {% else %}
    4     <p></p>
    5 {% endif %}
    1 {% for a in a_list %}
    2         <p>{{ a.name }}</p>
    3 {% endfor %}

    只有模板变量、字符串、整数和小数可以作为 {% ifequal %} 标签的参数,像字典、列表、布尔类型的是不能用在 {% ifequal %}中的,例如{% ifequal test [1,2,3] %}是错误的

    1 {# 比较2个参数的值,user1 user2 #}
    2     {% ifequal user1 user2 %}
    3         <p></p>
    4     {% else %}
    5         <p></p>
    6     {% endifequal %}

    {% include %}模板标签可以显示其他模板的内容{% include template_name %},例如

    {% include 'login.html' %}

    (二)模板继承

    可以在一个HTML页面中定义公共内容(网站logo等),其他页面继承这个模板

    1、定义基础模板base.html

    <!-- base.html -->
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>我的博客-所有博客列表</title>
    </head>
    <style>
    </style>
    <body>
    {% block content %}
    {% endblock %}
    <div align="center">python django 网站 2018 ©版权所有</div>
    </body>
    </html>
    {% block content %}

    {% endblock %}
    这个标签之间的内容是可以替换的

    2、继承,例如:下面这个就是

    第一行继承 base.html,后面的就是替换base.html  {% block content %}       {% endblock %} 标签之间的内容

    1 {% extends "base.html" %}
    2 {% block content %}
    3 <form action="/blog/team/" method="post">{% csrf_token %}
    4     <div align="center"><table >{{ form }}</table><br>
    5     <input type=submit></div>
    6 </form>
    7 <hr>
    8 {% endblock %}

    (三)模板渲染

    模板创建好后,可以用 context 来传递数据给它。 一个context是一系列变量和它们值的集合,类似于字典。

    例如: django.shortcuts 文件中的render函数

    def render(request, template_name, context=None, content_type=None, status=None, using=None):
        """
        Return a HttpResponse whose content is filled with the result of calling
        django.template.loader.render_to_string() with the passed arguments.
        """
        content = loader.render_to_string(template_name, context, request, using=using)
        return HttpResponse(content, content_type, status)

    第二个参数就是模板,第三个就是要传给模板的数据

    def login(request):
        return render(request,'login.html',{'form':LoginPostForm,})
  • 相关阅读:
    HDU 3555 Bomb (数位DP)
    ms sqlserver数据库主文件特别大怎么办
    w3wp.exe占用cpu特别高
    Excel的数据批量替换
    用Excel的分列功能格式化时间
    sql cte的使用
    数据结构
    http与浏览器学习
    长方形裁切优化与矩形物料排料
    架构知识
  • 原文地址:https://www.cnblogs.com/simple-free/p/9041738.html
Copyright © 2011-2022 走看看