zoukankan      html  css  js  c++  java
  • The Definitive Guide To Django 2 学习笔记(六) 第四章 模板 (二)使用模板系统

    模板系统不是django特有的,它是python的一个库,你可以在任何地方使用它。

    使用方法:

    1.使用 Template()方法创建Template对象。2.调用Template对象的render()方法。

    >>> from django import template
    >>> t = template.Template('My name is {{ name }}.')
    >>> c = template.Context({'name': 'Adrian'})
    >>> print t.render(c)
    My name is Adrian.
    >>> c = template.Context({'name': 'Fred'})
    >>> print t.render(c)
    My name is Fred.

    创建Template对象


    在mysite项目中,输入python manage.py shell 启动交互解释器。

    >>> from django.template import Template
    >>> t = Template('My name is {{ name }}.')
    >>> print t

    输出:

    <django.template.Template object at 0xb7d5f24c>

    0xb7d5f24c 每次都不一样,它是python内部的识别标识。

    如果代码有错,会出现错误提示。

    >>> from django.template import Template
    >>> t = Template('{% notatag %}')
    Traceback (most recent call last):
    File "<stdin>", line 1, in ?
    ...
    django.template.TemplateSyntaxError: Invalid block tag: 'notatag'

    block tag这里指代 {%notatag%}.

    系统触发了TemplateSyntaxError异常 因为以下情形:

    1.无效的tages

    2.无效的参数

    3.无效的过滤器

    4.无效的template syntax

    5.未闭合的tags

    展示模板

    创建完模板后,接下来就可以给模板一个Context,然后可以填充数据了:

    >>> from django.template import Context, Template
    >>> t = Template('My name is {{ name }}.')
    >>> c = Context({'name': 'Stephane'})
    >>> t.render(c)
    u'My name is Stephane.'

    需要指出的是这里的字符串是Unicode,这可以从字符串的前缀u看出来。

  • 相关阅读:
    解析Javascript事件冒泡机制
    LeetCode——Flatten Binary Tree to Linked List
    流动python
    HDU2586
    Cannot find ActionMappings or ActionFormBeans collection
    reactor设计模式
    简单的Ajax应用实例
    CString——Left、Right、Find、ReverseFind
    MATLAB新手教程
    八大排序算法总结
  • 原文地址:https://www.cnblogs.com/kfx2007/p/3425675.html
Copyright © 2011-2022 走看看