<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    海上月明

    editer by sun
    posts - 162, comments - 51, trackbacks - 0, articles - 8
       :: 首頁 :: 新隨筆 ::  :: 聚合  :: 管理

    The Django template language: For template authors

    Posted on 2006-11-30 22:15 pts 閱讀(2452) 評論(0)  編輯  收藏 所屬分類: Django

    The Django template language: For template authors

    This covers Django version 0.95 and the development version. Old docs: 0.90, 0.91

    Django's template language is designed to strike a balance between power and ease. It's designed to feel comfortable to those used to working with HTML. If you have any exposure to other text-based template languages, such as Smarty or CheetahTemplate, you should feel right at home with Django's templates.

    Django的模板語言力求在易用和功能之間達到平衡,如果用戶熟悉HTML語言,則使用起來會很舒服,如果你有其他文本式的模板語言使用經驗,如Smarty、CheetahTemplate,在使用Django模板時你也會感覺非常熟悉。

    Templates

    A template is simply a text file. It can generate any text-based format (HTML, XML, CSV, etc.).

    一個簡單的文本格式文件就是一個模板,它可以是html、xml、csv等各種文本格式。

    A template contains variables, which get replaced with values when the template is evaluated, and tags, which control the logic of the template.

    模板文件包括變量,標簽。變量在模板執行時被替換為實際值,標簽用力控制模板執行邏輯。

    Below is a minimal template that illustrates a few basics. Each element will be explained later in this document.:

    下面是一個簡單的基本模板元素應用示例,各元素意義將在后面陸續講解。
    
    {% extends "base_generic.html" %}
    
    {% block title %}{{ section.title }}{% endblock %}
    
    {% block content %}
    <h1>{{ section.title }}</h1>
    
    {% for story in story_list %}
    <h2>
      <a href="{{ story.get_absolute_url }}">
        {{ story.headline|upper }}
      </a>
    </h2>
    <p>{{ story.tease|truncatewords:"100" }}</p>
    {% endfor %}
    {% endblock %}
    

    Philosophy

    Why use a text-based template instead of an XML-based one (like Zope's TAL)? We wanted Django's template language to be usable for more than just XML/HTML templates. At World Online, we use it for e-mails, JavaScript and CSV. You can use the template language for any text-based format.

    Oh, and one more thing: Making humans edit XML is sadistic!

    為什么使用文本格式而不是xml格式,比如Zope的TAL?因為我們希望Django模板語言不僅僅適用XML/HTML,我們還希望它可適用于Email、js教本、csv,可以是任何文本格式。還有一點,編輯XML有點不人道。

    Variables

    變量

    Variables look like this: {{ variable }}. When the template engine encounters a variable, it evaluates that variable and replaces it with the result.

    變量使用格式是{{變量名}}。但模板解釋器遇到它時,就會用變量的實際值來替換。

    Use a dot (.) to access attributes of a variable.

    可以使用逗點"."獲取變量屬性。

    Behind the scenes

    實現細節

    Technically, when the template system encounters a dot, it tries the following lookups, in this order:

    • Dictionary lookup
    • Attribute lookup
    • Method call
    • List-index lookup

    在技術上,但模板解釋器遇到逗點操作符時,他會按照一下順序查找屬性值:

    • 字典
    • 變量
    • 方法
    • 索引

    In the above example, {{ section.title }} will be replaced with the title attribute of the section object.

    在上面的例子中,{{section.title}}會被section對象的title屬性值替換掉。

    If you use a variable that doesn't exist, the template system will insert the value of the TEMPLATE_STRING_IF_INVALID setting, which is set to '' (the empty string) by default.

    如果一個變量不存在,解釋器會插入設置文件中TEMPLATE_STRING_IF_INVALID的值,默認是空字符串。

    See Using the built-in reference, below, for help on finding what variables are available in a given template.

    Filters

    過濾器

    You can modify variables for display by using filters.

    你可以使用過濾器來改變變量值的最終顯示結果。

    Filters look like this: {{ name|lower }}. This displays the value of the {{ name }} variable after being filtered through the lower filter, which converts text to lowercase. Use a pipe (|) to apply a filter.

    過濾器的形式為:{{name|lower}},它將對變量name施用過濾器lower,即將name值全部小寫。"|"表示應用過濾器。

    Filters can be "chained." The output of one filter is applied to the next. {{ text|escape|linebreaks }} is a common idiom for escaping text contents, then converting line breaks to <p> tags.

    過濾器可以嵌套,前一個輸出可以作為下一個過濾器的輸入。比如{{text|escape|linebreaks}}

    Some filters take arguments. A filter argument looks like this: {{ bio|truncatewords:"30" }}. This will display the first 30 words of the bio variable. Filter arguments always are in double quotes.

    有些過濾器可以有參數,如{{bio|truncatewords:"30"}},它將僅顯示bio變量值的前30個字符,參數通常使用雙引號。

    The Built-in filter reference below describes all the built-in filters.

    Tags

    標簽

    Tags look like this: {% tag %}. Tags are more complex than variables: Some create text in the output, some control flow by performing loops or logic, and some load external information into the template to be used by later variables.

    標簽形式為{% tag %},標簽使用要比變量更麻煩,標簽可以實現文本輸出、循環執行、邏輯判斷等功能,也可以存儲一些信息以備后續變量使用。

    Some tags require beginning and ending tags (i.e. {% tag %} ... tag contents ... {% endtag %}). The Built-in tag reference below describes all the built-in tags. You can create your own tags, if you know how to write Python code.

    有些標簽需要開始和結束標記,如果你掌握python編程,也可以設計你自己的標簽。

    Comments

    注釋

    New in Django development version

    是Django新版本的功能

    To comment-out part of a template, use the comment syntax: {# #}.

    注釋格式為{# 注釋內容 #}

    For example, this template would render as 'hello':

    如,下面模板僅輸出"hello"。

    {# greeting #}hello
    

    A comment can contain any template code, invalid or not. For example:

    注釋可以包含任意模板代碼,不論正確與否,比如:

    {# {% if foo %}bar{% else %} #}
    

    Template inheritance

    模板繼承

    The most powerful -- and thus the most complex -- part of Django's template engine is template inheritance. Template inheritance allows you to build a base "skeleton" template that contains all the common elements of your site and defines blocks that child templates can override.

    繼承是Django模板應用中一項功能強大、使用最復雜的一項機制,模板繼承可以讓你先建立一個基礎架構模板,包含你站點中的所有公共元素,個性元素可以定義為blocks塊,供子模板去繼承。

    It's easiest to understand template inheritance by starting with an example:

    下面就讓我們從最簡單的模板擴展例子開始:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <link rel="stylesheet" href="style.css" />
        <title>{% block title %}My amazing site{% endblock %}</title>
    </head>
    
    <body>
        <div id="sidebar">
            {% block sidebar %}
            <ul>
                <li><a href="/">Home</a></li>
                <li><a href="/blog/">Blog</a></li>
            </ul>
            {% endblock %}
        </div>
    
        <div id="content">
            {% block content %}{% endblock %}
        </div>
    </body>
    </html>
    

    This template, which we'll call base.html, defines a simple HTML skeleton document that you might use for a simple two-column page. It's the job of "child" templates to fill the empty blocks with content.

    這個模板文件我們保存為base.html,它定義了一個基本的文檔框架,包含兩個列項,子模板的任務就是填充需要自定義的項。

    In this example, the {% block %} tag defines three blocks that child templates can fill in. All the block tag does is to tell the template engine that a child template may override those portions of the template.

    在例子中,{% block %}標簽定義了需要子模板填充的項,block標簽就是要告訴模板解釋器,這些內容是需要子模板自定義的項目。

    A child template might look like this:

    一個子模板可能看起來像這樣:

    {% extends "base.html" %}
    
    {% block title %}My amazing blog{% endblock %}
    
    {% block content %}
    {% for entry in blog_entries %}
        <h2>{{ entry.title }}</h2>
        <p>{{ entry.body }}</p>
    {% endfor %}
    {% endblock %}
    

    The {% extends %} tag is the key here. It tells the template engine that this template "extends" another template. When the template system evaluates this template, first it locates the parent -- in this case, "base.html".

    {% extends %}標簽在這里很重要,它告訴解釋器這個模板文件繼承自另外一個模板,當模板解釋器碰到這個標簽時,它會首先定位父模板,即base.html。

    At that point, the template engine will notice the three {% block %} tags in base.html and replace those blocks with the contents of the child template. Depending on the value of blog_entries, the output might look like:

    在這種情況下,解釋器會用子模板中定義的block內容替換掉父模板中的相應的內容。根據對象blog_entries具體內容,子模板輸出的內容可能像下面這樣:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <link rel="stylesheet" href="style.css" />
        <title>My amazing blog</title>
    </head>
    
    <body>
        <div id="sidebar">
            <ul>
                <li><a href="/">Home</a></li>
                <li><a href="/blog/">Blog</a></li>
            </ul>
        </div>
    
        <div id="content">
            <h2>Entry one</h2>
            <p>This is my first entry.</p>
    
            <h2>Entry two</h2>
            <p>This is my second entry.</p>
        </div>
    </body>
    </html>
    

    Note that since the child template didn't define the sidebar block, the value from the parent template is used instead. Content within a {% block %} tag in a parent template is always used as a fallback.

    請注意,盡管子模板中沒有定義sidebar塊,但解釋器自動將父模板的sidebar塊內容繼承下來。父模板中block塊的內容總是作為所有子模板中的缺省內容。

    You can use as many levels of inheritance as needed. One common way of using inheritance is the following three-level approach:

    你可以使用你需要的任意層次的繼承層次。通常的繼承用法需要下面的三個步驟:

    • Create a base.html template that holds the main look-and-feel of your site. 創建一個base.html文件,包括你站點的主要元素
    • Create a base_SECTIONNAME.html template for each "section" of your site. For example, base_news.html, base_sports.html. These templates all extend base.html and include section-specific styles/design. 為每種不同需要建立單獨的子模板文件,如base_news.html、base_sports.html,他們繼承自base.html,包含有特別的樣式和內容。
    • Create individual templates for each type of page, such as a news article or blog entry. These templates extend the appropriate section template. ******

    This approach maximizes code reuse and makes it easy to add items to shared content areas, such as section-wide navigation.

    Here are some tips for working with inheritance:

    • If you use {% extends %} in a template, it must be the first template tag in that template. Template inheritance won't work, otherwise. {% extends %}
    • 標簽必須是模板文件中的第一個標簽。
    • More {% block %} tags in your base templates are better. Remember, child templates don't have to define all parent blocks, so you can fill in reasonable defaults in a number of blocks, then only define the ones you need later. It's better to have more hooks than fewer hooks.
    • 盡量多在base模板文件中定義block塊,子模板不必全部重定義父模板中的每一個block塊。
    • If you find yourself duplicating content in a number of templates, it probably means you should move that content to a {% block %} in a parent template.
    • 如果你發現有重復定義的內容,那就意味著你也許要將重復的項目定義為父模板中的一個block塊。
    • If you need to get the content of the block from the parent template, the {{ block.super }} variable will do the trick. This is useful if you want to add to the contents of a parent block instead of completely overriding it.
    • 如果需要引用父模板中的block塊,可以使用block.super變量,特別是在你需要增加父標簽內容而不是覆蓋父標簽內容時。

    Finally, note that you can't define multiple {% block %} tags with the same name in the same template. This limitation exists because a block tag works in "both" directions. That is, a block tag doesn't just provide a hole to fill -- it also defines the content that fills the hole in the parent. If there were two similarly-named {% block %} tags in a template, that template's parent wouldn't know which one of the blocks' content to use.

    最后,需要注意幾點:一個模板文件中不能有多個相同的block標簽變量名。

    Using the built-in reference

    Django's admin interface includes a complete reference of all template tags and filters available for a given site. To see it, go to your admin interface and click the "Documentation" link in the upper right of the page.

    The reference is divided into 4 sections: tags, filters, models, and views.

    Django模板內置四種引用類型:tags,filters,models,views。

    The tags and filters sections describe all the built-in tags (in fact, the tag and filter references below come directly from those pages) as well as any custom tag or filter libraries available.

    The views page is the most valuable. Each URL in your site has a separate entry here, and clicking on a URL will show you:

    • The name of the view function that generates that view.
    • A short description of what the view does.
    • The context, or a list of variables available in the view's template.
    • The name of the template or templates that are used for that view.

    Each view documentation page also has a bookmarklet that you can use to jump from any page to the documentation page for that view.

    Because Django-powered sites usually use database objects, the models section of the documentation page describes each type of object in the system along with all the fields available on that object.

    Taken together, the documentation pages should tell you every tag, filter, variable and object available to you in a given template.

    Custom tag and filter libraries

    Certain applications provide custom tag and filter libraries. To access them in a template, use the {% load %} tag:

    {% load comments %}
    
    {% comment_form for blogs.entries entry.id with is_public yes %}
    

    In the above, the load tag loads the comments tag library, which then makes the comment_form tag available for use. Consult the documentation area in your admin to find the list of custom libraries in your installation.

    The {% load %} tag can take multiple library names, separated by spaces. Example:

    load標簽后可跟多個庫名,用空格格開,如:

    {% load comments i18n %}
    

    Custom libraries and template inheritance

    When you load a custom tag or filter library, the tags/filters are only made available to the current template -- not any parent or child templates along the template-inheritance path.

    引入的標簽庫僅對當前模板文件有效。

    For example, if a template foo.html has {% load comments %}, a child template (e.g., one that has {% extends "foo.html" %}) will not have access to the comments template tags and filters. The child template is responsible for its own {% load comments %}.

    This is a feature for the sake of maintainability and sanity.

    Built-in tag and filter reference

    For those without an admin site available, reference for the stock tags and filters follows. Because Django is highly customizable, the reference in your admin should be considered the final word on what tags and filters are available, and what they do.

    Built-in tag reference

    內置的幾種標簽:

    block

    Define a block that can be overridden by child templates. See Template inheritance for more information.

    定義可繼承的block塊。

    comment

    Ignore everything between {% comment %} and {% endcomment %}

    定義注釋塊。

    cycle

    Cycle among the given strings each time this tag is encountered.

    ??????

    Within a loop, cycles among the given strings each time through the loop:

    {% for o in some_list %}
        <tr class="{% cycle row1,row2 %}">
            ...
        </tr>
    {% endfor %}
    

    Outside of a loop, give the values a unique name the first time you call it, then use that name each successive time through:

    <tr class="{% cycle row1,row2,row3 as rowcolors %}">...</tr>
    <tr class="{% cycle rowcolors %}">...</tr>
    <tr class="{% cycle rowcolors %}">...</tr>
    

    You can use any number of values, separated by commas. Make sure not to put spaces between the values -- only commas.

    debug

    Output a whole load of debugging information, including the current context and imported modules.

    extends

    Signal that this template extends a parent template.

    This tag can be used in two ways:

    extends標簽可以有兩種用法:

    • {% extends "base.html" %} (with quotes) uses the literal value "base.html" as the name of the parent template to extend.
    • 繼承自某個模板文件,后跟文件名
    • {% extends variable %} uses the value of variable. If the variable evaluates to a string, Django will use that string as the name of the parent template. If the variable evaluates to a Template object, Django will use that object as the parent template.
    • 繼承自某個模板文件,后跟變量名

    See Template inheritance for more information.

    filter

    Filter the contents of the variable through variable filters.

    Filters can also be piped through each other, and they can have arguments -- just like in variable syntax.

    Sample usage:

    {% filter escape|lower %}
        This text will be HTML-escaped, and will appear in all lowercase.
    {% endfilter %}
    

    firstof

    Outputs the first variable passed that is not False. Outputs nothing if all the passed variables are False.

    輸出第一個True值。如果全為False,什么也不輸出。

    Sample usage:

    {% firstof var1 var2 var3 %}
    

    This is equivalent to:

    {% if var1 %}
        {{ var1 }}
    {% else %}{% if var2 %}
        {{ var2 }}
    {% else %}{% if var3 %}
        {{ var3 }}
    {% endif %}{% endif %}{% endif %}
    

    for

    Loop over each item in an array. For example, to display a list of athletes given athlete_list:

    <ul>
    {% for athlete in athlete_list %}
        <li>{{ athlete.name }}</li>
    {% endfor %}
    </ul>
    

    You can also loop over a list in reverse by using {% for obj in list reversed %}.

    可以用反序循環:{% for obj in list reversed %}

    The for loop sets a number of variables available within the loop:

    Variable Description
    forloop.counter The current iteration of the loop (1-indexed)當前循環次數 1開始
    forloop.counter0 The current iteration of the loop (0-indexed)當前循環次數 0開始
    forloop.revcounter The number of iterations from the end of the loop (1-indexed)循環剩余次數,1開始
    forloop.revcounter0

    The number of iterations from the end of the loop (0-indexed)循環剩余次數,1開始

    forloop.first True if this is the first time through the loop,如果是第一次循環則為真
    forloop.last True if this is the last time through the loop,如果是組后一次循環則為真
    forloop.parentloop For nested loops, this is the loop "above" the current one

    if

    The {% if %} tag evaluates a variable, and if that variable is "true" (i.e. exists, is not empty, and is not a false boolean value) the contents of the block are output:

    {% if athlete_list %}
        Number of athletes: {{ athlete_list|length }}
    {% else %}
        No athletes.
    {% endif %}
    

    In the above, if athlete_list is not empty, the number of athletes will be displayed by the {{ athlete_list|length }} variable.

    As you can see, the if tag can take an optional {% else %} clause that will be displayed if the test fails.

    if tags may use and, or or not to test a number of variables or to negate a given variable:

    {% if athlete_list and coach_list %}
        Both athletes and coaches are available.
    {% endif %}
    
    {% if not athlete_list %}
        There are no athletes.
    {% endif %}
    
    {% if athlete_list or coach_list %}
        There are some athletes or some coaches.
    {% endif %}
    
    {% if not athlete_list or coach_list %}
        There are no athletes or there are some coaches (OK, so
        writing English translations of boolean logic sounds
        stupid; it's not our fault).
    {% endif %}
    
    {% if athlete_list and not coach_list %}
        There are some athletes and absolutely no coaches.
    {% endif %}
    

    if tags don't allow and and or clauses within the same tag, because the order of logic would be ambiguous. For example, this is invalid:

    if標簽不允許同時使用and 和 or 語句,如果確實需要,可以使用嵌套的if語句。

    {% if athlete_list and coach_list or cheerleader_list %}
    

    If you need to combine and and or to do advanced logic, just use nested if tags. For example:

    {% if athlete_list %}
        {% if coach_list or cheerleader_list %}
            We have athletes, and either coaches or cheerleaders!
        {% endif %}
    {% endif %}
    

    Multiple uses of the same logical operator are fine, as long as you use the same operator. For example, this is valid:

    {% if athlete_list or coach_list or parent_list or teacher_list %}
    

    ifchanged

    Check if a value has changed from the last iteration of a loop.

    檢查在循環中變量的值或某屬性是否改變,如改變,則輸出相應內容。

    The 'ifchanged' block tag is used within a loop. It has two possible uses.

    1. Checks its own rendered contents against its previous state and only displays the content if it has changed. For example, this displays a list of days, only displaying the month if it changes:

      <h1>Archive for {{ year }}</h1>
      
      {% for date in days %}
          {% ifchanged %}<h3>{{ date|date:"F" }}</h3>{% endifchanged %}
          <a href="{{ date|date:"M/d"|lower }}/">{{ date|date:"j" }}</a>
      {% endfor %}
      
    2. New in Django development version. If given a variable, check whether that variable has changed. For example, the following shows the date every time it changes, but only shows the hour if both the hour and the date has changed:

      {% for date in days %}
          {% ifchanged date.date %} {{ date.date }} {% endifchanged %}
          {% ifchanged date.hour date.date %}
              {{ date.hour }}
          {% endifchanged %}
      {% endfor %}
      

    ifequal

    Output the contents of the block if the two arguments equal each other.

    如果兩個變量內容相同,輸出相應內容。

    Example:

    {% ifequal user.id comment.user_id %}
        ...
    {% endifequal %}
    

    As in the {% if %} tag, an {% else %} clause is optional.

    The arguments can be hard-coded strings, so the following is valid:

    {% ifequal user.username "adrian" %}
        ...
    {% endifequal %}
    

    It is only possible to compare an argument to template variables or strings. You cannot check for equality with Python objects such as True or False. If you need to test if something is true or false, use the if tag instead.

    不能使用ifequal比較python對象,如true、false,如果需要,可以使用if標簽。

    ifnotequal

    Just like ifequal, except it tests that the two arguments are not equal.
    如果不相等,基本同ifequal。

    include

    Loads a template and renders it with the current context. This is a way of "including" other templates within a template.

    The template name can either be a variable or a hard-coded (quoted) string, in either single or double quotes.

    This example includes the contents of the template "foo/bar.html":

    {% include "foo/bar.html" %}
    

    This example includes the contents of the template whose name is contained in the variable template_name:

    {% include template_name %}
    

    An included template is rendered with the context of the template that's including it. This example produces the output "Hello, John":

    • Context: variable person is set to "john".

    • Template:

      {% include "name_snippet.html" %}
      
    • The name_snippet.html template:

      Hello, {{ person }}
      

    See also: {% ssi %}.

    load

    Load a custom template tag set.

    See Custom tag and filter libraries for more information.

    now

    Display the date, formatted according to the given string.

    Uses the same format as PHP's date() function (http://php.net/date) with some custom extensions.

    Available format strings:

    Format character Description Example output
    a 'a.m.' or 'p.m.' (Note that this is slightly different than PHP's output, because this includes periods to match Associated Press style.) 'a.m.'
    A 'AM' or 'PM'. 'AM'
    B Not implemented.
    d Day of the month, 2 digits with leading zeros. '01' to '31'
    D Day of the week, textual, 3 letters. 'Fri'
    f Time, in 12-hour hours and minutes, with minutes left off if they're zero. Proprietary extension. '1', '1:30'
    F Month, textual, long. 'January'
    g Hour, 12-hour format without leading zeros. '1' to '12'
    G Hour, 24-hour format without leading zeros. '0' to '23'
    h Hour, 12-hour format. '01' to '12'
    H Hour, 24-hour format. '00' to '23'
    i Minutes. '00' to '59'
    I Not implemented.
    j Day of the month without leading zeros. '1' to '31'
    l Day of the week, textual, long. 'Friday'
    L Boolean for whether it's a leap year. True or False
    m Month, 2 digits with leading zeros. '01' to '12'
    M Month, textual, 3 letters. 'Jan'
    n Month without leading zeros. '1' to '12'
    N Month abbreviation in Associated Press style. Proprietary extension. 'Jan.', 'Feb.', 'March', 'May'
    O Difference to Greenwich time in hours. '+0200'
    P Time, in 12-hour hours, minutes and 'a.m.'/'p.m.', with minutes left off if they're zero and the special-case strings 'midnight' and 'noon' if appropriate. Proprietary extension. '1 a.m.', '1:30 p.m.', 'midnight', 'noon', '12:30 p.m.'
    r RFC 822 formatted date. 'Thu, 21 Dec 2000 16:01:07 +0200'
    s Seconds, 2 digits with leading zeros. '00' to '59'
    S English ordinal suffix for day of the month, 2 characters. 'st', 'nd', 'rd' or 'th'
    t Number of days in the given month. 28 to 31
    T Time zone of this machine. 'EST', 'MDT'
    U Not implemented.
    w Day of the week, digits without leading zeros. '0' (Sunday) to '6' (Saturday)
    W ISO-8601 week number of year, with weeks starting on Monday. 1, 23
    y Year, 2 digits. '99'
    Y Year, 4 digits. '1999'
    z Day of the year. 0 to 365
    Z Time zone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive. -43200 to 43200

    Example:

    It is {% now "jS F Y H:i" %}
    

    Note that you can backslash-escape a format string if you want to use the "raw" value. In this example, "f" is backslash-escaped, because otherwise "f" is a format string that displays the time. The "o" doesn't need to be escaped, because it's not a format character.:

    It is the {% now "jS o\f F" %}
    

    (Displays "It is the 4th of September" %}

    regroup

    Regroup a list of alike objects by a common attribute.

    !使用一個屬性來對list分組。

    This complex tag is best illustrated by use of an example: say that people is a list of Person objects that have first_name, last_name, and gender attributes, and you'd like to display a list that looks like:

    • Male:
      • George Bush
      • Bill Clinton
    • Female:
      • Margaret Thatcher
      • Condoleezza Rice
    • Unknown:
      • Pat Smith

    The following snippet of template code would accomplish this dubious task:

    {% regroup people by gender as grouped %}
    <ul>
    {% for group in grouped %}
        <li>{{ group.grouper }}
        <ul>
            {% for item in group.list %}
            <li>{{ item }}</li>
            {% endfor %}
        </ul>
    {% endfor %}
    </ul>
    

    As you can see, {% regroup %} populates a variable with a list of objects with grouper and list attributes. grouper contains the item that was grouped by; list contains the list of objects that share that grouper. In this case, grouper would be Male, Female and Unknown, and list is the list of people with those genders.

    Note that {% regroup %} does not work when the list to be grouped is not sorted by the key you are grouping by! This means that if your list of people was not sorted by gender, you'd need to make sure it is sorted before using it, i.e.:

    {% regroup people|dictsort:"gender" by gender as grouped %}
    

    spaceless

    Normalizes whitespace between HTML tags to a single space. This includes tab characters and newlines.

    Example usage:

    {% spaceless %}
        <p>
            <a href="foo/">Foo</a>
        </p>
    {% endspaceless %}
    

    This example would return this HTML:

    <p> <a href="foo/">Foo</a> </p>
    

    Only space between tags is normalized -- not space between tags and text. In this example, the space around Hello won't be stripped:

    只對標簽之間的空格有效,對標簽和文本之間的空格無效。如下面Hello前后的空格不會被格式化。

    {% spaceless %}
        <strong>
            Hello
        </strong>
    {% endspaceless %}
    

    ssi

    Output the contents of a given file into the page.

    引入一個給定文件的內容。

    Like a simple "include" tag, {% ssi %} includes the contents of another file -- which must be specified using an absolute path -- in the current page:

    必須使用一個絕對路徑:

    {% ssi /home/html/ljworld.com/includes/right_generic.html %}
    

    If the optional "parsed" parameter is given, the contents of the included file are evaluated as template code, within the current context:

    如果parsed參數被應用,引用的文件被看作是一個模板文件:

    {% ssi /home/html/ljworld.com/includes/right_generic.html parsed %}
    

    Note that if you use {% ssi %}, you'll need to define ALLOWED_INCLUDE_ROOTS in your Django settings, as a security measure.

    要使用ssi標簽,需要在setting文件中設定ALLOWED_INCLUDE_ROOTS的值。

    See also: {% include %}.

    templatetag

    Output one of the syntax characters used to compose template tags.

    Since the template system has no concept of "escaping", to display one of the bits used in template tags, you must use the {% templatetag %} tag.

    The argument tells which template bit to output:

    Argument Outputs
    openblock {%
    closeblock %}
    openvariable {{
    closevariable }}
    openbrace {
    closebrace }
    opencomment {#
    closecomment #}

    Note: opencomment and closecomment are new in the Django development version.

    widthratio

    For creating bar charts and such, this tag calculates the ratio of a given value to a maximum value, and then applies that ratio to a constant.


    ??????

    For example:

    <img src="bar.gif" height="10" width="{% widthratio this_value max_value 100 %}" />
    

    Above, if this_value is 175 and max_value is 200, the the image in the above example will be 88 pixels wide (because 175/200 = .875; .875 * 100 = 87.5 which is rounded up to 88).

    Built-in filter reference

    add

    Adds the arg to the value.

    addslashes

    Adds slashes. Useful for passing strings to JavaScript, for example.

    capfirst

    Capitalizes the first character of the value.

    center

    Centers the value in a field of a given width.

    cut

    Removes all values of arg from the given string.

    date

    Formats a date according to the given format (same as the now tag).

    default

    If value is unavailable, use given default.

    default_if_none

    If value is None, use given default.

    dictsort

    Takes a list of dicts, returns that list sorted by the property given in the argument.

    dictsortreversed

    Takes a list of dicts, returns that list sorted in reverse order by the property given in the argument.

    divisibleby

    Returns true if the value is divisible by the argument.

    escape

    !!!

    Escapes a string's HTML. Specifically, it makes these replacements:

    • "&" to "&amp;"
    • < to "&lt;"
    • > to "&gt;"
    • '"' (double quote) to '&quot;'
    • "'" (single quote) to '&#39;'

    filesizeformat

    Format the value like a 'human-readable' file size (i.e. '13 KB', '4.1 MB', '102 bytes', etc).

    first

    Returns the first item in a list.

    fix_ampersands

    Replaces ampersands with &amp; entities.

    floatformat

    Rounds a floating-point number to one decimal place -- but only if there's a decimal part to be displayed. For example:

    • 36.123 gets converted to 36.1
    • 36.15 gets converted to 36.2
    • 36 gets converted to 36

    get_digit

    Given a whole number, returns the requested digit of it, where 1 is the right-most digit, 2 is the second-right-most digit, etc. Returns the original value for invalid input (if input or argument is not an integer, or if argument is less than 1). Otherwise, output is always an integer.

    join

    Joins a list with a string, like Python's str.join(list).

    length

    Returns the length of the value. Useful for lists.

    length_is

    Returns a boolean of whether the value's length is the argument.

    linebreaks

    Converts newlines into <p> and <br /> tags.

    linebreaksbr

    Converts newlines into <br /> tags.

    linenumbers

    Displays text with line numbers.

    ljust

    Left-aligns the value in a field of a given width.

    Argument: field size

    lower

    Converts a string into all lowercase.

    make_list

    Returns the value turned into a list. For an integer, it's a list of digits. For a string, it's a list of characters.

    phone2numeric

    Converts a phone number (possibly containing letters) to its numerical equivalent. For example, '800-COLLECT' will be converted to '800-2655328'.

    The input doesn't have to be a valid phone number. This will happily convert any string.

    pluralize

    Returns a plural suffix if the value is not 1. By default, this suffix is 's'.

    Example:

    You have {{ num_messages }} message{{ num_messages|pluralize }}.
    

    For words that require a suffix other than 's', you can provide an alternate suffix as a parameter to the filter.

    Example:

    You have {{ num_walruses }} walrus{{ num_walrus|pluralize:"es" }}.
    

    For words that don't pluralize by simple suffix, you can specify both a singular and plural suffix, separated by a comma.

    Example:

    You have {{ num_cherries }} cherr{{ num_cherries|pluralize:"y,ies" }}.
    

    pprint

    A wrapper around pprint.pprint -- for debugging, really.

    random

    Returns a random item from the list.

    removetags

    Removes a space separated list of [X]HTML tags from the output.

    rjust

    Right-aligns the value in a field of a given width.

    Argument: field size

    slice

    Returns a slice of the list.

    Uses the same syntax as Python's list slicing. See http://diveintopython.org/native_data_types/lists.html#odbchelper.list.slice for an introduction.

    Example: {{ some_list|slice:":2" }}

    slugify

    Converts to lowercase, removes non-word characters (alphanumerics and underscores) and converts spaces to hyphens. Also strips leading and trailing whitespace.

    stringformat

    Formats the variable according to the argument, a string formatting specifier. This specifier uses Python string formating syntax, with the exception that the leading "%" is dropped.

    See http://docs.python.org/lib/typesseq-strings.html for documentation of Python string formatting

    striptags

    Strips all [X]HTML tags.

    time

    Formats a time according to the given format (same as the now tag).

    timesince

    Formats a date as the time since that date (i.e. "4 days, 6 hours").

    Takes an optional argument that is a variable containing the date to use as the comparison point (without the argument, the comparison point is now). For example, if blog_date is a date instance representing midnight on 1 June 2006, and comment_date is a date instance for 08:00 on 1 June 2006, then {{ comment_date|timesince:blog_date }} would return "8 hours".

    timeuntil

    Similar to timesince, except that it measures the time from now until the given date or datetime. For example, if today is 1 June 2006 and conference_date is a date instance holding 29 June 2006, then {{ conference_date|timeuntil }} will return "28 days".

    Takes an optional argument that is a variable containing the date to use as the comparison point (instead of now). If from_date contains 22 June 2006, then {{ conference_date|timeuntil:from_date }} will return "7 days".

    title

    Converts a string into titlecase.

    truncatewords

    Truncates a string after a certain number of words.

    Argument: Number of words to truncate after

    unordered_list

    Recursively takes a self-nested list and returns an HTML unordered list -- WITHOUT opening and closing <ul> tags.

    The list is assumed to be in the proper format. For example, if var contains ['States', [['Kansas', [['Lawrence', []], ['Topeka', []]]], ['Illinois', []]]], then {{ var|unordered_list }} would return:

    <li>States
    <ul>
            <li>Kansas
            <ul>
                    <li>Lawrence</li>
                    <li>Topeka</li>
            </ul>
            </li>
            <li>Illinois</li>
    </ul>
    </li>
    

    upper

    Converts a string into all uppercase.

    urlencode

    Escapes a value for use in a URL.

    urlize

    Converts URLs in plain text into clickable links.

    將文本中的url轉換為可點擊的鏈接。

    urlizetrunc

    Converts URLs into clickable links, truncating URLs to the given character limit.

    Argument: Length to truncate URLs to

    wordcount

    Returns the number of words.

    wordwrap

    Wraps words at specified line length.

    Argument: number of characters at which to wrap the text

    yesno

    Given a string mapping values for true, false and (optionally) None, returns one of those strings according to the value:

    Value Argument Outputs
    True "yeah,no,maybe" yeah
    False "yeah,no,maybe" no
    None "yeah,no,maybe" maybe
    None "yeah,no" "no" (converts None to False if no mapping for None is given)

    Other tags and filter libraries

    其他的標簽和過濾器庫

    Django comes with a couple of other template-tag libraries that you have to enable explicitly in your INSTALLED_APPS setting and enable in your template with the {% load %} tag.

    django.contrib.humanize

    A set of Django template filters useful for adding a "human touch" to data. See the humanize documentation.

    django.contrib.markup

    A collection of template filters that implement these common markup languages:

    • Textile
    • Markdown
    • ReST (ReStructured Text)

    Comments

    評論

    Stefan H. Holek September 6, 2005 at 2:43 a.m.

    For those who want to use Page Templates in Django: http://zope.org/Members/shh/DjangoPageTe...

    Krasna Halopti October 26, 2005 at 6:51 a.m.

    "For simplicity, if tags do not allow 'and' clauses; use nested if tags instead".

    How are 'and' clauses less simple than 'or' clauses? They seem as simple to use and to parse. Can someone please enlighten? Sorry if I've missed something obvious.

    Simon Willison October 26, 2005 at 7:34 a.m.

    Krasna: "and" and "or" are both simple, but defining the way they interact isn't. Consider {{ if a and b or c }} - how should the clauses be grouped? Introducing some kind of explicit grouping syntax seems a bit over the top, but if we have a precedence rule instead it might not match what people are trying to do in all cases.

    That said, we could add support for "and" that requires it not to be mixed with "or". I'm not sure if there are any good arguments against doing so.

    Krasna Halopti October 26, 2005 at 10:39 a.m.

    Simon: By 'explicit grouping syntax' I presume you mean parentheses? While they may not be totally trivial to implement, I wouldn't have categorised them as 'over the top' ;-)

    Antti Kaihola December 11, 2005 at 10:24 a.m.

    It seems that the regrouping criterion can also be an expression:

    {% regroup items by starttime.year as items_by_year %}

    Damien December 12, 2005 at 12:42 p.m.

    I don't mean to nitpick but why the ".html" extension for these templates? Although HTML may be the most commonly generated output, these templates are not HTML files. Doesn't this just confuse things? Wouldn't something like ".dt" (Django template) make more sense?

    Not that it's a big deal and it is just a convention, but since it didn't really make sense to me I was curious as to why that was chosen. Oh and thanks for the awesome framework!

    Adrian Holovaty December 12, 2005 at 1:03 p.m.

    Damien: We chose ".html" because that activates syntax highlighting in HTML editors.

    Joe December 15, 2005 at 11:15 a.m.

    "To make it easy to figure out what's available in a given site, the admin interface has a complete reference of all the template goodies available to that site."

    But only if you append '/doc/' to the end of your admin url. Should be mentioned really.

    Ibon December 22, 2005 at 2:53 p.m.

    Is it posible in any way, to use PSP (mod_python templates) and still use all the other good things in django ?
    Thas it make senes ?

    (I've thiscovered django today ... I'm sorry I didn't ear 12 months earlier)

    Armin Ronacher December 24, 2005 at 6:34 a.m.

    Cool Thing. But i'm missing an elif equivalent.

    Multiple Children December 26, 2005 at 3:22 a.m.

    So I keep looking through the docs to figure out how to have one parent with multiple children templates filling in differnt parts of the parent. Is this something that one needs the include command to do? Can it be done at all.

    Basically what I am trying to figure out how to do is to create one parent site template with 'slots' for a sidebar and main page content.

    The problem is bthis: I have a sidebar (for starters..I would like a choice of several) and several basic page layouts (say a 2 col layout with just sidebar and content or a 3 col layout with sidebar, content and navigation info) and several different types of content I want to display in each of these layouts. I want to create two base templates (two, three column layouts) and choose a sidebar and main content to extend these templates. But if I put the sidebar info in the layout template I have to duplicate the same sidebar for both the 2 and 3 col layouts. If I put it in the content template I have to duplicate the sidbar for every type of main content.

    I know this isn't the place to ask for answers (though I wouldn't mind one) but I think this problem is pretty general (it also appears anytime you have two slots you want to fill independently in a base template) and it would be nice to either see this covered or a statement that it is impossible.

    logicnazi December 26, 2005 at 4:01 a.m.

    I was the one who just posted the last comment with a title instead of name.

    Anyway, I think the answer to my question is just by dynamically setting the template to extend and chaining the templates in some arbitrary order. I haven't checked this but if it works it should be in the docs since I have seen the same question (unanswered) on the mailing list.

    Essentially as I understand it I could do the following:
    layout_2col.html
    with slots for content and left_sidebar (so would layout_3col.html)

    Now given Lsidebar3.html and content5.html we just dynamically make Lsidebar3.html extend layout_2col.html and then content5.html extend Lsidebar3.html and we get what we want.

    It's a bit unintuitive so I think it should be in the docs.

    Antti Kaihola December 28, 2005 at 10:32 a.m.

    For an example of how to use non-HTML templates, see http://www.djangoproject.com/documentati...

    It seems to me that template files still always need the .html extension. Or is there a simple way to load a template called "template.csv" or "template.txt"?

    Antti Kaihola December 28, 2005 at 10:55 a.m.

    "Custom tag and filter libraries" needs more specific instructions. Here's a working example:

    If you have an app called "looksgood" inside project "world", you need:
    world/apps/looksgood/templatetags/__init__.py (empty file)
    world/apps/looksgood/templatetags/beautifiers.py

    In beautifiers.py, you could have:

    from django.core import template
    register = template.Library()
    def tidy(value): return
    clean_and_polish(value)
    register.filter(tidy)

    In world/apps/looksgood/views.py you need:

    from world.apps.looksgood.templatetags import beautifiers

    Now you can use your custom filter in templates. For example, in world/apps/looksgood/templates/index.html you can say:

    {% load beautifiers %}
    {{ ugly_object.value|tidy }}

    bruce January 2, 2006 at 2:10 p.m.

    I can't get the built-in reference from the admin page. There is a comment from 'Joe December 15, 2005 ' on the Django site that says to append /doc/ to the admin url, and this acknowledges the existence of the reference but says that python docutils lib is required, but after installing this I still get the same message. Does Django have to be told somewhere that this is installed or does this library need to be included somewhere to work?

    Erich Schubert January 11, 2006 at 2:21 p.m.

    Any chance that django will at some point support a template language like TAL that helps ensuring valid XML output?
    "but they can generate any text-based format (HTML, XML, CSV, etc.)." -- yeah, except it's incredibly wrong and likely to fail to generate XML/XHTML with a text-based approach. Use a tree-based approach and serialize it to XML, ensuring a valid file... And safe us the woes of incorrect encodings, characters not translated to entities etc.

    Right now I'd go with TurboGears because of that - having flawless XML is very important to me, being able to generate CSV or plain text with the same template language is not.

    Adrian Holovaty January 11, 2006 at 2:40 p.m.

    Erich Schubert: You're free to use any template language you want with Django, because the template layer is completely decoupled from the view layer. If you like the Kid template system, feel free to use it!

    Jean-Yves Migeon January 20, 2006 at 5:20 p.m.

    All in all, the more I use django the more I feel comfortable with it. I find the syntax and template engine easely understandable, with tons of possibilities to go with.

    Simple, I was using mod_python with PSP alone, but was really disappointed by the syntax for templates, defining blocks are really tricky.

    Tried turbogears, and to some extent Zope, but I felt in love with django, plain and simple.

    Just a thought though: is there any way to test the presence of a defined string in a list, and/or return the number of appearence in it, like .count method? Didn't find anything of this sort in filters, perhaps I missed something?

    Just sharing, if anybody interested. Could be used for lists of errors, when working with forms for example.

    def count(value, arg):
    "Returns the number of appearance of value in a list or string"
    return value.count(arg)

    Should work with strings too. Add this to defaultfilters.py, don't forget the register.filter(count)... should do fine.

    Tony McD January 26, 2006 at 12:48 a.m.

    Erich,
    Look at the first comment by Stefan, Zope PageTemplates work fine in Django (with some, minor and zope-specific, limitations)! ;) - very very handy for migration purposes...

    Sean Reifschneider January 28, 2006 at 11:40 a.m.

    The "Template Inheritance" section does not discuss how "extends" finds templates. Do they have to exist in the same directory? Does it search up towards the docroot?

    Wilson February 9, 2006 at 11:06 a.m.

    Sean: It looks in the directories specified by the TEMPLATE_DIRS setting in your project's settings file, in the order you specify them.

    andi February 13, 2006 at 3:20 p.m.

    ..only i willed to say in my (just censored) comment , is that use politican as example in the programming tutorial, is generally not good idea. Especially current mr. president. Its all.

    Y-Coci February 20, 2006 at 8:37 a.m.

    Hi all,

    I'm using { % extends "parent" % } and I'm getting a "...template does not exist error" for the parent template.

    I have the two templates in the same directory and they are in a subfolder of my template directory.

    Has enyone had or solved this problem?

    I saw this same problem raised on the google forum but there was no solution?

    mailman integrator February 28, 2006 at 10:22 a.m.

    Used smarty, and like this a lot.

    My only complaint is that it's not compatible with the mailman templates(e.g %(template_variable) ). Need a fast practical solution there.

    I need to remotely get a page over HTTP that has a lot of SSI-dependent stuff, then run that output through template processor to insert content from mailman.

    rob Slotboom March 8, 2006 at 6:16 p.m.

    Please provide an example for stringformat.

    I want to use
    return "%.2f" % total_amount
    to get two decimals but I don't know how.

    rob slotboom March 10, 2006 at 4:37 a.m.

    Is it possible to add some initial value to a forloop.counter?

    This would be handy when using limit and offset.

    More general, is is possible to use template vars as values for calculations:
    {{ var1 }} + {{ var 2 }}

    Jean March 11, 2006 at 1:29 a.m.

    Y-Coci: I have the same problem but no solution yet...

    Frankie March 15, 2006 at 11:09 a.m.

    """More general, is is possible to use template vars as values for calculations:
    {{ var1 }} + {{ var 2 }}"""

    This belongs in views.py.

    Topdeck March 21, 2006 at 7:03 p.m.

    Y-Coci, Jean: If the template you want to extend is in a subdirectory of your templates directory, you need to indicate that in your extend:
    {% extends "subdirectory/parentTemplate" %}

    Quentin April 9, 2006 at 4:59 a.m.

    I'm interested in dictionary lookup using variables.

    If I try

    {% for i in my_list %}
    {{ my_dict.i }}
    {% endfor %}

    then I think it will look for mydict["i"] but not mydict[i] - is that right?
    Any way to do the latter?

    Thanks.

    Adrian Holovaty April 9, 2006 at 6:13 p.m.

    Quentin: Nope, there's no way to do dynamic lookup (where the dictionary key is a variable). You'll have to write a custom tag or filter to do that.

    Carina April 12, 2006 at 2:15 p.m.

    Are there any filters available for translating a greater range of entities than just ('escape' filter's) ampersand, double quote, less than, and greater than?

    Fcnd April 13, 2006 at 8:26 p.m.

    It would be nice to add some examples to each filter like
    Divisibleby

    {{ 34|divisibleby:2 }}

    it may be obvious to someone but I got stuck for a while there

    wyleu April 16, 2006 at 2:40 p.m.

    as mentioned in the 'Using the built-in reference' section you can view your views...

    not without setting ADMIN_FOR = ('myproject.settings',) in settings.py you can't!

    Otherwise you will just see Jump to site with nothing listed...

    it's worth the effort.

    Daniel Lindsley April 29, 2006 at 9:53 p.m.

    One thing that would be highly beneficial might be some suggestion as to how to link media files within the template.

    I, as a rule, prefer having a seperate development and production environment and would like to keep the media between them seperate. ;) I'm guessing that I'm going to have to write a custom tag that will check the settings file, establish if it's live or dev and provide the correct URL.

    Can anyone suggest a better solution? (I would like to avoid writing a tag is there's already a good way to do it.)

    Andrew K. May 2, 2006 at 10:35 p.m.

    Maybe I'm an idiot, but I see no clear way to iterate just a certain number of times, or more generally with any int attribute. Let's say I want to print "Hi." nine times, is there a range() sort of filter that I can use to do this?

    Andrew K. May 2, 2006 at 10:47 p.m.

    Oh, and W.R.T. the and/or question, if you don't want to introduce a grouping syntax then don't, but it's kinda crippled without both. Ands precede ors; boolean algebra has been like that for a century. Nobody will complain, and if they do, kick them onto Wikipedia for a few hours. Although some expressions may get a little tricky, literally every boolean function is representable in and/or form. If you add in parenthesis in later revisions, then the behavior won't be at all unexpected either.

    Julia May 3, 2006 at 12:09 a.m.

    I encountered the same "template does not exist" error as Y-Coci and Jean. The subdirectory was not the problem, it was the ".html" in the template name, which is demonstrated in the examples. When I changed the statement to {% extends "base" %} I no longer got the error.

    Jeff Croft May 7, 2006 at 8:55 p.m.

    Julia-

    I suspect you are on an older (non magic-removal) version of Django. The newer versions require the .html extensions, whereas the older versions require you don't include it. This document is written for magic-removal syntax. See the top of the page for links to documentation on older versions.

    sandro turriate May 11, 2006 at 10 a.m.

    Quentin:
    Concerning dynamic dictionary lookup:
    I have years={2006: 4} (amount of posts for a given year)
    I wanted to use
    {% for year in years %}
    {{ year }} has {{ years.year }} posts.
    {% endfor %}
    in order to get: 2006 has 4 posts.
    it didn't work.

    Instead of giving my context a dictionary I now give it a list of tuples:
    >>> years.items()
    [(2006, 4)]
    and now my template does this:
    {% for year in years %}
    {{ year.0 }} has {{ year.1 }} posts.
    {% endfor %}
    2006 has 4 posts...it worked!

    alan May 21, 2006 at 10:16 a.m.

    There is a nasty gotcha with internationalization and template extending.

    You have to do {% load i18n %} before doing {% extends "xyz" %} if you want {% get_language_code as xyz %} to work. I don't know where the "xyz" variable goes, but it just doesn't appear!

    Will June 7, 2006 at 5:58 p.m.

    Is it possible to integrate OpenLaszlo with Django at the template layer?

    sdsd June 28, 2006 at 1:52 p.m.

    sdsds

    Tonya July 1, 2006 at 10:50 a.m.

    The current implementation of pluralize is pretty handy, but it doesn't appear from this page to handle the plural forms of words that require more than just adding an 's' to the end of the word (fly/flies, ox/oxen). How about changing it or adding another function that's something like:

    {% pluralize num_geese "goose" "geese" %}

    It could have a default form without a third argument and appends the 's' to the string in the second argument if the number is not 1:

    {% pluralize num_cars "car" %}
    outputs "cars"

    Pupeno July 15, 2006 at 3:11 p.m.

    For those wanting TAL (TALES, METALES, Zope, Zope Page Template, ZPT... keywords for the same thing) a good hint would be to try simpletal http://www.owlfish.com/software/simpleTA...
    I am doing some experimenting with it right now.

    Kumar McMillan July 18, 2006 at 3:14 p.m.

    someone eluded to this in the comments above but I figured I should point it out too. There is no mention in the documentation of the "for" tag that you can't do:

    {% for k,v in myitems %}
    {{ k }} = {{ v }}

    and it took me a while to figure it out because the error gets completely swallowed, looping through myitems but not setting any variables! Maybe there is mention of it somewhere else that I missed but as a pythonist learning django this seemed like the most intuitive thing to do. All I can imagine is that there was a speed concern for why it's not implemented.

    the fix is:

    {% for k_and_v in myitems %}
    {{ k_and_v.0 }} = {{ k_and_v.1 }}

    uggh. or write a custom tag.

    Sybren July 20, 2006 at 5:43 a.m.

    If you want to use 'openbrace' etc., use {% templatetag openbrace %}

    test July 25, 2006 at 2:25 a.m.

    test

    John July 29, 2006 at 11:34 p.m.

    It would be useful to mention somewhere (e.g. the section on custom tags) that there is also technical documentation for templates, including how to extend them: http://www.djangoproject.com/documentati...

    Otherwise, it can be tricky for technical readers coming from the Django tutorial to this more technical page.

    jmu August 9, 2006 at 4:37 a.m.

    Built-in filter ADD needs an example. I needed to subtract from value, and since there was no SUBTRACT filter, I used notation: {{ value|add:-2 }} which did not work.
    However, after trying few options find the way to use it:
    {{ value|add:"-2" }}

    This special case should be documented

    Konrad August 15, 2006 at 7:39 a.m.

    So if a variable doesn't exist it quietly inserts the empty string, but if I do lookup on a None it throws a VariableDoesNotExist error? When I have var.method.key.whatever and one of those lookups is None, I just want the whole thing to be None. Is that possible? For example in Velocity you do this by adding ! before the $!variableName.

    dt August 24, 2006 at 8:07 p.m.

    I noticed there is "first" built-in filter but not "last". Was there any specific reason not including it? I know it's not hard to include this to my local copy of Django but I feel I shouldn't modify the framework's code.

    Any thought on including this as a feature?

    django@dougma.com August 24, 2006 at 11:36 p.m.

    dt:
    I think its a good I dea to include a last filter.
    I would like to point out that you can extend the template system with your own, so if you would like to add it for your own projects, go ahead. There is no need to modify the framework to get this feature.

    Guillaume Pratte August 25, 2006 at 9:27 a.m.

    I don't understand how dictsort works. I think the documentation should be more elaborate on this subject.

    Gustavo August 25, 2006 at 3:55 p.m.

    I can′t figure out how to use admin tags on my non admin templates. I load the tags correctly with
    {% load admin_list %} or {% load admin_modify %}
    but all the tags require a cl object. How can I use the
    date_hierarchy tag?

    Jojo August 29, 2006 at 8:03 p.m.

    I saw mentions of using SimpleTAL and the Zope 3 Page Templates if one happens to have Zope 3 installed, but what about the regular free-standing version of Zope Page Templates from http://zpt.sourceforge.net/ ?

    Andrew September 13, 2006 at 5:08 p.m.

    More explanation for custom tags:

    As of 0.95:
    If you want to use the decorator @register.filter you need these two lines:

    from django.template import Library
    register = Library()

    Paul September 22, 2006 at 12:12 a.m.

    For the record, in order to iterate through dicts you can use something like the following:

    {% for item in mydict.items %}
    ..{{ item.0 }} <---- This is the key.
    ..{{ item.1 }} <---- This is the value.
    {% endfor %}

    This seems to work with Django 0.95, whereas the previous docs (which were missing the ".items" part) do not.

    Obviously this uses the dict.items () method which returns a list of pairs of items from the dict.

    Helmar October 2, 2006 at 1:47 p.m.

    The friendly folks on IRC pointed out to me that a view should never have a base/parent template, only child templates. This is important to know for those 'crossing over' from other languages, and who think more in the way of a traditional 'include'.

    IOW, Django works bottom-up, so if the view calls up a child template, the (% extends base.html %} tells it to render that and replace any possible blocks in it. So, the child calls the parent ('base.html') rather than the other way round.

    anjocee#gmail.com October 12, 2006 at 9:27 p.m.

    When I find the filter "LJUST", I just use it uppercase style as in this document, but django tells me cannot find LJUST...

    At last, I realized my mistake and use 'ljust', all right...

    Suggestion: give the filters the original case in each title.

    Fredrik October 20, 2006 at 10:41 a.m.

    I guess you're supposed to cut and paste the filter names ;-)

    akaihola November 9, 2006 at 11:53 a.m.

    It should probably be mentioned that the new-style {# #} comment tags only work single-line. Use {% comment %} {% endcomment %} for multi-line comments.

    It would be also nice if explanations for both commenting styles referred to each other.

    pb@e-scribe.com November 12, 2006 at 4:19 p.m.

    Agree with akaihola -- that one-line limitation might even deserve a "Note" callout since it's going to be a surprising limitation to the newcomer. Perhaps it would help to explain that a comment in this style is essentially a single tag, and that tags can't contain newlines?

    Afternoon November 22, 2006 at 9:37 a.m.

    There's a typo in the walrus pluralize example.

    'You have {{ num_walruses }} walrus{{ num_walrus|pluralize:"es" }}.' should be 'You have {{ num_walruses }} walrus{{ num_walruses|pluralize:"es" }}.'

    mark November 22, 2006 at 2:58 p.m.

    It's worth noting that the time filter only covers aABfgGiPs from the list of specifiers under NOW. If you want the full set (to do something like "d/m/Y H:i:s"), use the date filter instead, which covers the complete list.

    If you use |time for a format specifier it doesn't cover, you'll get an error like 'TimeFormat' object has no attribute d.

    Dave Abrahams November 26, 2006 at 12:04 p.m.

    How are slice tags supposed to be used?
    The only place I know how to use a list is in another construct that accepts a list, e.g. {% for ... %}. But neither

    {% for n in {{object_list|slice "4:"}} %}

    nor

    {% for n in object_list|slice "4:" %}

    seem to parse correctly.

    dougn November 26, 2006 at 6:06 p.m.

    Proper use of slice filter:

    {% for n in object_list|slice:"4:" %}


    Powered by Zoundry

    主站蜘蛛池模板: 精品免费tv久久久久久久| 久久久久亚洲精品无码网址色欲| 国产黄片不卡免费| 亚洲国产精品第一区二区三区| 亚洲A∨精品一区二区三区下载| 夜夜爽免费888视频| 亚洲精品欧美综合四区| 四虎永久在线免费观看| 特级无码毛片免费视频| 亚洲第一区在线观看| a毛片免费播放全部完整| 亚洲AV日韩AV天堂久久| 91香蕉国产线在线观看免费| 亚洲欧洲日产韩国在线| 成人无遮挡裸免费视频在线观看| 亚洲精华国产精华精华液好用| 手机看片久久国产免费| 一边摸一边爽一边叫床免费视频| 亚洲色婷婷一区二区三区| 免费福利电影在线观看| 亚洲国产日韩在线成人蜜芽| 天天摸天天操免费播放小视频| 一级黄色片免费观看| 亚洲高清日韩精品第一区| 成年人性生活免费视频| 美女被爆羞羞网站免费| 亚洲夜夜欢A∨一区二区三区| 一级成人a毛片免费播放| 亚洲中文字幕一二三四区| 国产一区二区免费在线| 国产精品免费大片| 亚洲jizzjizz在线播放久| 日韩亚洲国产二区| 久久久久久成人毛片免费看| 亚洲不卡影院午夜在线观看| 亚洲第一页日韩专区| 最近中文字幕完整免费视频ww | 国产精品亚洲二区在线观看| 在线A级毛片无码免费真人| 黄人成a动漫片免费网站| 亚洲成AV人片在WWW色猫咪|