• Django学习笔记4模板


    1.页面的设计和Python的代码分离开会更干净简洁更容易维护。 我们可以使用 Django的 模板系统 (Template System)来实现这种模式,

    模板是一个文本,用于分离文档的表现形式和内容。 模板定义了占位符以及各种用于规范文档该如何显示的各部分基本逻辑(模板标签)。

    2.  模板通常用于产生HTML,但是Django的模板也能产生任何基于文本格式的文档。//若是安卓可以xml???

    <!DOCTYPE html>
    <html>
    <head>
        <title>Ordering notice</title>
    </head>
    <body>
    <h1>Ordering notice</h1>
    <p>Dear {{ person_name }},</p>
    
    <p>Thanks for placing an order from {{ company }}.It's scheduled to ship on {{ ship_date|date:"F j,Y" }}.</p>
    <p>Here are the items you've ordered:</p>
    <u1>
        {% for item in item_list %}
        <li>{{ item }}</li>
    </u1>
    {% if ordered_warranty %}
        <p>You did't order a warranty,so you 're on your own when the products inevitably stop working.</p>
    {% else %}
    {% endif %} <p>Sincerely,<br />{{ company }}</p> </body> </html>

    两个大括号  {{person_name}} 称为在变量 ,大括号和百分比包围的文本, {% for item in item_list %} 是模板标签(template tag),标签的定义比较明确,仅通知模版系统完成某些工作,for标签类似for语句

    3.

    在Python代码中使用Django模板的最基本方式如下:
    1. 可以用原始的模板代码字符串创建一个 Template 对象, Django同样支持用指定模板文件路径的方式来创
    建 Template 对象;
    2. 调用模板对象的render方法,并且传入一套变量context。它将返回一个基于模板的展现字符串,模板中
    的变量和标签会被context值替换

    from django.http import HttpResponse
    from django.template import Template,Context
    # Create your views here.
    import datetime
    
    def hello(request):
        return HttpResponse("Hello world")
    
    def current_datetime(request):
        now = datetime.datetime.now()
        t=Template("<html><body>It is now{{ current_date }}.</body></html>")
        html=t.render(Context({'current_date':now}))
        return HttpResponse(html)

     

     

  • 相关阅读:
    [置顶] 文件批量重命名(工具)
    zookeeper源码分析之三客户端发送请求流程
    java set转list,数组与list的转换
    分布式电子邮件系统设计--转载
    redis 模糊删除实现
    eclipse 使用jetty调试时,加依赖工程的源码调试方法
    社交产品后端架构设计--转载
    solr服务器的查询过程
    What is corresponding Cron expression to fire in every X seconds, where X > 60? --转载
    zookeeper源码分析之二客户端启动
  • 原文地址:https://www.cnblogs.com/zzblee/p/4266474.html
Copyright © 2020-2023  润新知