zoukankan      html  css  js  c++  java
  • django--模板

    reference: http://www.djangobook.com/en/2.0/chapter04.html

    Those are the fundamentals of using the Django template system: just write a template string, create a Templateobject, create a Context, and call the render() method.

    • Any text surrounded by a pair of braces (e.g., {{ person_name }}) is a variable. This means “insert the value of the variable with the given name.” (How do we specify the values of the variables? We’ll get to that in a moment.)

    • Any text that’s surrounded by curly braces and percent signs (e.g., {% if ordered_warranty %}) is atemplate tag. The definition of a tag is quite broad: a tag just tells the template system to “do something.”

    • {{ ship_date|date:"F j, Y" }}, we’re passing the ship_date variable to the date filter, giving the date filter the argument "F j, Y". The date filter formats dates in a given format, as specified by that argument. Filters are attached using a pipe character (|), as a reference to Unix pipes.

    Here is the most basic way you can use Django’s template system in Python code:

    1. Create a Template object by providing the raw template code as a string.
    2. Call the render() method of the Template object with a given set of variables (the context). This returns a fully rendered template as a string, with all of the variables and template tags evaluated according to the context.

    In code, here’s what that looks like:

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

    The manage.py shellcommand has one key difference: before starting the interpreter, it tells Django which settings file to use. Many parts of Django, including the template system, rely on your settings, and you won’t be able to use them unless the framework knows which settings to use.

    Rendering a Template

    Once you have a Template object, you can pass it data by giving it a context. A context is simply a set of template variable names and their associated values. A template uses this to populate its variables and evaluate its tags.

    
    

    A context is represented in Django by the Context class, which lives in the django.template module. Its constructor takes one optional argument: a dictionary mapping variable names to variable values. Call the Template object’srender() method with the context to “fill” the template:

    One thing we should point out here is that the return value of t.render(c) is a Unicode object – not a normal Python string.
  • 相关阅读:
    百度Apollo安装说明
    Ubuntu 16.04 kinetic 下安装turtlebot2
    三维点云地图构建方法
    jupyter中添加conda环境
    Pyplot教程(深度学习入门3)
    linux下安装tomcat,部署项目
    linux下修改系统时间
    手把手集成web端手写公式功能
    如何查看端口是被哪个程序占用的
    Bootstrap的优先级、选择器、伪类
  • 原文地址:https://www.cnblogs.com/zxpo/p/3820407.html
Copyright © 2011-2022 走看看