zoukankan      html  css  js  c++  java
  • Django中模板使用

    第一步:配置

    1.在工程中创建模板目录templates。
    2.在settings.py配置文件中修改TEMPLATES配置项的DIRS值:
    TEMPLATES = [
    {
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [os.path.join(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',
    ],
    },
    },
    ]

    第二步:定义模板
    1.在templates目录中新建一个模板文件,如index.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Title</title>
    </head>
    <body>
    <h1>{{ city }}</h1>
    </body>
    </html>


    第三步:模板渲染
    调用模板分为两步骤:
    1.找到模板 loader.get_template(模板文件在模板目录中的相对路径) -> 返回模板对象
    2渲染模板 模板对象.render(context=None, request=None) -> 返回渲染后的html文本字符串 context 为模板变量字典,默认值为None request 为请求对象,默认值为None

    方式一:
    from django.http import HttpResponse
    from django.template import loader
    def index(request):
    # 1.获取模板
    template=loader.get_template('index.html')
    context={'city': '北京'}
    # 2.渲染模板
    return HttpResponse(template.render(context))

    方式二(推荐):
    render(request对象, 模板文件路径, 模板数据字典)

    from django.shortcuts import render
    def index(request):
    context={'city': '北京'}
    return render(request,'index.html',context)

    与flask相比模板语句的不同

    列表和字典只能通过点语法来操作
    <h1>{{ adict.name }}</h1> 注意字典的取值方法
    <h1>{{ alist.0 }}</h1> 注意列表的取值方法

    注意:运算符左右两侧不能紧挨变量或常量,必须有空格。
    {% if a == 1 %} # 正确

    多行注释
    {% comment %}
    ...
    {% endcomment %}

    模板的继承中:{{ block.super }}用于获取父模板中block的内容

  • 相关阅读:
    在其他机器上安装mysql和hive后设置hive元数据存储为mysql
    MapReduce作业切片和Shuffle
    sns 批量清除脚本
    PHP 汉字 转换成 拼音
    PHPCMS V9 和其他应用同步
    nginx启动,重启,关闭命令
    Linux下zip unzip的用户示例 解压到指定目录
    nginx phpcms rewrite规则
    javascript 里面嵌套方法
    数制及其转换
  • 原文地址:https://www.cnblogs.com/yunlongaimeng/p/9788240.html
Copyright © 2011-2022 走看看