Django

Code

Changeset 145

Show
Ignore:
Timestamp:
07/17/05 10:15:26 (3 years ago)
Author:
adrian
Message:

Fixed typo in template docs -- Thanks, Nicholas Riley and Robin Munn!

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • django/trunk/docs/templates.txt

    r112 r145  
    2626 
    2727    {% extends "base_generic" %} 
    28      
     28 
    2929    {% block title %}{{ section.title }}{% endblock %} 
    30      
     30 
    3131    {% block content %} 
    3232    <h1>{{ section.title }}</h1> 
    33      
     33 
    3434    {% for story in story_list %} 
    3535    <h2> 
     
    4848encounters a variable, it evaluates that variable and replaces the variable with 
    4949the result.  Many variables will be structures with named attributes; you can 
    50 "drill down" into these structures with dots (``.``), so in the above example  
     50"drill down" into these structures with dots (``.``), so in the above example 
    5151``{{ section.title }}`` will be replaced with the ``title`` attribute of the 
    5252``section`` object. 
     
    5858are available in a given template. 
    5959 
    60 Variables may be modified before being displayed by **filters**.   
     60Variables may be modified before being displayed by **filters**. 
    6161 
    6262What's a filter? 
     
    6969We use the pipe character to apply filters to emphasize the analogy with filters 
    7070on a water pipe: text enters one side, has some operation performed on it, and 
    71 "flows" out the other side.  Filters may be "chained"; the output of one filter  
    72 applied to the next: ``{{ text|escape|linebreaks }}`` is a common idiom for  
     71"flows" out the other side.  Filters may be "chained"; the output of one filter 
     72applied to the next: ``{{ text|escape|linebreaks }}`` is a common idiom for 
    7373escaping text contents and then converting line breaks to ``<p>`` tags. 
    7474 
     
    105105        <title>{% block title %}My Amazing Site{% endblock %}</title> 
    106106    </head> 
    107      
     107 
    108108    <body> 
    109109        <div id="sidebar"> 
     
    115115            {% endblock %} 
    116116        </div> 
    117          
     117 
    118118        <div id="content"> 
    119119            {% block content %}{% endblock %} 
    120120        </div> 
    121121    </body> 
    122      
     122 
    123123This template, which we'll call ``base.html`` defines a simple HTML skeleton 
    124124document that you might use for a simple two-column page.  This template 
    125 won't actually be used directly on any pages, but other "child" templates will  
    126 extend it and fill in the empty blocks with content.  
    127  
    128 I've used the ``{% block %}`` tag to define the three blocks that child templates  
    129 will fill in.  All that the ``block`` tag does is to signal to the template engine  
     125won't actually be used directly on any pages, but other "child" templates will 
     126extend it and fill in the empty blocks with content. 
     127 
     128I've used the ``{% block %}`` tag to define the three blocks that child templates 
     129will fill in.  All that the ``block`` tag does is to signal to the template engine 
    130130that a child template may override those portions of the template. 
    131131 
     
    133133 
    134134    {% extends "base" %} 
    135      
     135 
    136136     {% block title %}My Amazing Blog{% endblock %} 
    137      
     137 
    138138     {% block content %} 
    139      
     139 
    140140     {% for entry in blog_entries %} <h2>{{ entry.title }}</h2> <p>{{ entry.body 
    141141    }}</p> {% endfor %} 
    142      
     142 
    143143     {% endblock %} 
    144      
     144 
    145145The ``{% extends %}`` tag is the key here; it tells the template engine that 
    146146this template "extends" another template. When this template is evaluated, 
     
    160160        <title>My Amazing Blog</title> 
    161161    </head> 
    162      
     162 
    163163    <body> 
    164164        <div id="sidebar"> 
     
    168168            </ul> 
    169169        </div> 
    170          
     170 
    171171        <div id="content"> 
    172172            <h2>Entry one</h2> 
    173173            <p>This is my first entry.</p> 
    174              
     174 
    175175            <h2>Entry two</h2> 
    176176            <p>This is my second entry.</p> 
     
    189189 
    190190    * More ``{% block %}`` tags in your base templates are better.  Remember, 
    191       child templates do not have to define all parent blocks, so you can  
     191      child templates do not have to define all parent blocks, so you can 
    192192      fill in reasonable defaults in a number of blocks, then only define 
    193193      the ones you need later on. 
    194        
    195     * If you find yourself reproducing the same content in a number of  
    196       documents, it probably means you should move that content to a  
     194 
     195    * If you find yourself reproducing the same content in a number of 
     196      documents, it probably means you should move that content to a 
    197197      new ``{% block %}`` in a parent template. 
    198        
     198 
    199199    * We often prefer to use three-level inheritance: a single base template 
    200200      for the entire site, a set of mid-level templates for each section of 
    201201      the site, and then the individual templates for each page.  This 
    202       maximizes code reuse, and makes it easier to add items to shared  
     202      maximizes code reuse, and makes it easier to add items to shared 
    203203      content areas (like section-wide navigation). 
    204        
     204 
    205205    * If you need to get the content of the block from the parent template, 
    206206      the ``{{ block.super }}`` variable will do the trick.  This is useful 
    207       if you want to add to the contents of a parent block instead of  
     207      if you want to add to the contents of a parent block instead of 
    208208      completely overriding it. 
    209        
     209 
    210210Using the built-in reference 
    211211============================ 
     
    248248 
    249249    {% load comments %} 
    250      
     250 
    251251    {% comment_form for blogs.entries entry.id with is_public yes %} 
    252      
     252 
    253253In the above, the ``load`` tag loads the ``comments`` tag library, which then 
    254254makes the ``comment_form`` tag available for use.  Consult the documentation 
     
    269269    Define a block that can be overridden by child templates.  See `Template 
    270270    inheritance`_ for more information. 
    271      
     271 
    272272``comment`` 
    273273    Ignore everything between ``{% comment %}`` and ``{% endcomment %}`` 
    274      
     274 
    275275``cycle`` 
    276276    Cycle among the given strings each time this tag is encountered. 
    277      
     277 
    278278    Within a loop, cycles among the given strings each time through 
    279279    the loop:: 
    280      
     280 
    281281        {% for o in some_list %} 
    282282            <tr class="{% cycle row1,row2 %}"> 
     
    284284            </tr> 
    285285        {% endfor %} 
    286      
     286 
    287287    Outside of a loop, give the values a unique name the first time you call it, 
    288288    then use that name each successive time through:: 
    289      
     289 
    290290            <tr class="{% cycle row1,row2,row3 as rowcolors %}">...</tr> 
    291291            <tr class="{% cycle rowcolors %}">...</tr> 
    292292            <tr class="{% cycle rowcolors %}">...</tr> 
    293      
     293 
    294294    You can use any number of values, separated by commas. Make sure not to put 
    295295    spaces between the values -- only commas. 
    296      
     296 
    297297``debug`` 
    298298    Output a whole load of debugging information, including the current context and 
    299299    imported modules. 
    300      
     300 
    301301``extends`` 
    302302    Signal that this template extends a parent template. 
    303      
     303 
    304304    This tag may be used in two ways: ``{% extends "base" %}`` (with quotes) uses 
    305305    the literal value "base" as the name of the parent template to extend, or ``{% 
    306306    extends variable %}`` uses the value of ``variable`` as the name of the parent 
    307307    template to extend. 
    308      
     308 
    309309    See `Template inheritance`_ for more information. 
    310      
     310 
    311311``filter`` 
    312     Filter the contents of the blog through variable filters. 
    313      
     312    Filter the contents of the variable through variable filters. 
     313 
    314314    Filters can also be piped through each other, and they can have arguments -- 
    315315    just like in variable syntax. 
    316      
     316 
    317317    Sample usage:: 
    318      
     318 
    319319        {% filter escape|lower %} 
    320320            This text will be HTML-escaped, and will appear in all lowercase. 
    321321        {% endfilter %} 
    322      
     322 
    323323``firstof`` 
    324324    Outputs the first variable passed that is not False.  Outputs nothing if all the 
    325325    passed variables are False. 
    326      
     326 
    327327    Sample usage:: 
    328      
     328 
    329329        {% firstof var1 var2 var3 %} 
    330          
     330 
    331331    This is equivalent to:: 
    332      
     332 
    333333        {% if var1 %} 
    334334            {{ var1 }} 
     
    338338            {{ var3 }} 
    339339        {% endif %}{% endif %}{% endif %} 
    340          
     340 
    341341    but obviously much cleaner! 
    342      
     342 
    343343``for`` 
    344344    Loop over each item in an array.  For example, to display a list of athletes 
    345345    given ``athlete_list``:: 
    346      
     346 
    347347        <ul> 
    348348        {% for athlete in athlete_list %} 
     
    350350        {% endfor %} 
    351351        </ul> 
    352      
     352 
    353353    You can also loop over a list in reverse by using ``{% for obj in list reversed %}``. 
    354      
     354 
    355355    The for loop sets a number of variables available within the loop: 
    356      
     356 
    357357        ==========================  ================================================ 
    358358        Variable                    Description 
     
    365365                                    current one 
    366366        ==========================  ================================================ 
    367      
     367 
    368368``if`` 
    369369    The ``{% if %}`` tag evaluates a variable, and if that variable is "true" (i.e. 
    370370    exists, is not empty, and is not a false boolean value) the contents of the 
    371371    block are output:: 
    372      
     372 
    373373        {% if athlete_list %} 
    374374            Number of athletes: {{ athlete_list|count }} 
     
    376376            No athletes. 
    377377        {% endif %} 
    378      
     378 
    379379    In the above, if ``athlete_list`` is not empty, the number of athletes will be 
    380380    displayed by the ``{{ athlete_list|count }}`` variable. 
    381      
     381 
    382382    As you can see, the ``if`` tag can take an option ``{% else %}`` clause that 
    383383    will be displayed if the test fails. 
    384      
     384 
    385385    ``if`` tags may use ``or`` or ``not`` to test a number of variables or to negate 
    386386    a given variable:: 
    387      
     387 
    388388        {% if not athlete_list %} 
    389389            There are no athletes. 
    390390        {% endif %} 
    391          
     391 
    392392        {% if athlete_list or coach_list %} 
    393393            There are some athletes or some coaches. 
    394394        {% endif %} 
    395          
     395 
    396396        {% if not athlete_list or coach_list %} 
    397             There are no athletes or there are some coaches (OK, so  
    398             writing English translations of boolean logic sounds  
     397            There are no athletes or there are some coaches (OK, so 
     398            writing English translations of boolean logic sounds 
    399399            stupid; it's not my fault). 
    400400        {% endif %} 
    401      
    402     For simplicity, ``if`` tags do not allow ``and`` clauses; use nested ``if``  
     401 
     402    For simplicity, ``if`` tags do not allow ``and`` clauses; use nested ``if`` 
    403403    tags instead:: 
    404      
     404 
    405405        {% if athlete_list %} 
    406406            {% if coach_list %} 
     
    409409            {% endif %} 
    410410        {% endif %} 
    411      
     411 
    412412``ifchanged`` 
    413413    Check if a value has changed from the last iteration of a loop. 
    414      
     414 
    415415    The 'ifchanged' block tag is used within a loop. It checks its own rendered 
    416416    contents against its previous state and only displays its content if the value 
    417417    has changed:: 
    418      
     418 
    419419        <h1>Archive for {{ year }}</h1> 
    420      
     420 
    421421        {% for date in days %} 
    422422        {% ifchanged %}<h3>{{ date|date:"F" }}</h3>{% endifchanged %} 
    423423        <a href="{{ date|date:"M/d"|lower }}/">{{ date|date:"j" }}</a> 
    424424        {% endfor %} 
    425      
     425 
    426426``ifnotequal`` 
    427427    Output the contents of the block if the two arguments do not equal each other. 
    428      
     428 
    429429    Example:: 
    430      
     430 
    431431        {% ifnotequal user.id_ comment.user_id %} 
    432432            ... 
    433433        {% endifnotequal %} 
    434      
     434 
    435435``load`` 
    436436    Load a custom template tag set. 
    437      
     437 
    438438    See `Custom tag and filter libraries`_ for more information. 
    439      
     439 
    440440``now`` 
    441441    Display the date, formatted according to the given string. 
    442      
     442 
    443443    Uses the same format as PHP's ``date()`` function; see http://php.net/date 
    444444    for all the possible values. 
    445      
     445 
    446446    Sample usage:: 
    447      
     447 
    448448        It is {% now "jS F Y H:i" %} 
    449      
     449 
    450450``regroup`` 
    451451    Regroup a list of alike objects by a common attribute. 
    452      
     452 
    453453    This complex tag is best illustrated by use of an example:  say that ``people`` 
    454454    is a list of ``Person`` objects that have ``first_name``, ``last_name``, and 
    455455    ``gender`` attributes, and you'd like to display a list that looks like: 
    456      
     456 
    457457        * Male: 
    458458            * George Bush 
     
    463463        * Unknown: 
    464464            * Janet Reno 
    465      
     465 
    466466    The following snippet of template code would accomplish this dubious task:: 
    467      
     467 
    468468        {% regroup people by gender as grouped %} 
    469469        <ul> 
     
    477477        {% endfor %} 
    478478        </ul> 
    479      
     479 
    480480    As you can see, ``{% regroup %}`` populates a variable with a list of objects 
    481481    with ``grouper`` and ``list`` attributes.  ``grouper`` contains the item that 
     
    483483    ``grouper``.  In this case, ``grouper`` would be ``Male``, ``Female`` and 
    484484    ``Unknown``, and ``list`` is the list of people with those genders. 
    485      
     485 
    486486    Note that ``{% regroup %}`` does not work when the list to be grouped is not 
    487487    sorted by the key you are grouping by!  This means that if your list of people 
    488488    was not sorted by gender, you'd need to make sure it is sorted before using it, 
    489489    i.e.:: 
    490      
     490 
    491491        {% regroup people|dictsort:"gender" by gender as grouped %} 
    492      
     492 
    493493``ssi`` 
    494494    Output the contents of a given file into the page. 
    495      
     495 
    496496    Like a simple "include" tag, the ``ssi`` tag includes the contents 
    497497    of another file -- which must be specified using an absolute page -- 
    498498    in the current page:: 
    499      
     499 
    500500        {% ssi /home/html/ljworld.com/includes/right_generic.html %} 
    501      
     501 
    502502    If the optional "parsed" parameter is given, the contents of the included 
    503503    file are evaluated as template code, with the current context:: 
    504      
     504 
    505505        {% ssi /home/html/ljworld.com/includes/right_generic.html parsed %} 
    506      
     506 
    507507``templatetag`` 
    508508    Output one of the bits used to compose template tags. 
    509      
     509 
    510510    Since the template system has no concept of "escaping", to display one of the 
    511511    bits used in template tags, you must use the ``{% templatetag %}`` tag. 
    512      
     512 
    513513    The argument tells which template bit to output: 
    514      
     514 
    515515        ==================  ======= 
    516516        Argument            Outputs 
     
    521521        ``closevariable``   ``}}`` 
    522522        ==================  ======= 
    523      
     523 
    524524``widthratio`` 
    525525    For creating bar charts and such, this tag calculates the ratio of a given value 
    526526    to a maximum value, and then applies that ratio to a constant. 
    527      
     527 
    528528    For example:: 
    529      
     529 
    530530        <img src='bar.gif' height='10' width='{% widthratio this_value max_value 100 %}' /> 
    531      
     531 
    532532    Above, if ``this_value`` is 175 and ``max_value`` is 200, the the image in the 
    533533    above example will be 88 pixels wide (because 175/200 = .875; .875 * 100 = 87.5 
     
    539539``add`` 
    540540    Adds the arg to the value 
    541      
     541 
    542542``addslashes`` 
    543543    Adds slashes - useful for passing strings to JavaScript, for example. 
    544      
     544 
    545545``capfirst`` 
    546546    Capitalizes the first character of the value 
    547      
     547 
    548548``center`` 
    549549    Centers the value in a field of a given width 
    550      
     550 
    551551``cut`` 
    552552    Removes all values of arg from the given string 
    553      
     553 
    554554``date`` 
    555555    Formats a date according to the given format (same as the ``now`` tag) 
    556      
     556 
    557557``default`` 
    558558    If value is unavailable, use given default 
    559      
     559 
    560560``dictsort`` 
    561561    Takes a list of dicts, returns that list sorted by the property given in the 
    562562    argument. 
    563      
     563 
    564564``dictsortreversed`` 
    565565    Takes a list of dicts, returns that list sorted in reverse order by the property 
    566566    given in the argument. 
    567      
     567 
    568568``divisibleby`` 
    569569    Returns true if the value is divisible by the argument 
    570      
     570 
    571571``escape`` 
    572572    Escapes a string's HTML 
    573      
     573 
    574574``filesizeformat`` 
    575575    Format the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB, 102 
    576576    bytes, etc). 
    577      
     577 
    578578``first`` 
    579579    Returns the first item in a list 
    580      
     580 
    581581``fix_ampersands`` 
    582582    Replaces ampersands with ``&amp;`` entities 
    583      
     583 
    584584``floatformat`` 
    585585    Displays a floating point number as 34.2 (with one decimal places) - but 
    586586    only if there's a point to be displayed 
    587      
     587 
    588588``get_digit`` 
    589589    Given a whole number, returns the requested digit of it, where 1 is the 
     
    591591    original value for invalid input (if input or argument is not an integer, 
    592592    or if argument is less than 1). Otherwise, output is always an integer. 
    593      
     593 
    594594``join`` 
    595595    Joins a list with a string, like Python's ``str.join(list)`` 
    596      
     596 
    597597``length`` 
    598598    Returns the length of the value - useful for lists 
    599      
     599 
    600600``length_is`` 
    601601    Returns a boolean of whether the value's length is the argument 
    602      
     602 
    603603``linebreaks`` 
    604604    Converts newlines into <p> and <br />s 
    605      
     605 
    606606``linebreaksbr`` 
    607607    Converts newlines into <br />s 
    608      
     608 
    609609``linenumbers`` 
    610610    Displays text with line numbers 
    611      
     611 
    612612``ljust`` 
    613613    Left-aligns the value in a field of a given width 
    614      
     614 
    615615    **Argument:** field size 
    616      
     616 
    617617``lower`` 
    618618    Converts a string into all lowercase 
    619      
     619 
    620620``make_list`` 
    621621    Returns the value turned into a list. For an integer, it's a list of 
    622622    digits. For a string, it's a list of characters. 
    623      
     623 
    624624``phone2numeric`` 
    625625    Takes a phone number and converts it in to its numerical equivalent 
    626      
     626 
    627627``pluralize`` 
    628628    Returns 's' if the value is not 1, for '1 vote' vs. '2 votes' 
    629      
     629 
    630630``pprint`` 
    631631    A wrapper around pprint.pprint -- for debugging, really 
    632      
     632 
    633633``random`` 
    634634    Returns a random item from the list 
    635      
     635 
    636636``removetags`` 
    637637    Removes a space separated list of [X]HTML tags from the output 
    638      
     638 
    639639``rjust`` 
    640640    Right-aligns the value in a field of a given width 
    641      
     641 
    642642    **Argument:** field size 
    643      
     643 
    644644``slice`` 
    645645    Returns a slice of the list. 
    646      
     646 
    647647    Uses the same syntax as Python's list slicing; see 
    648648    http://diveintopython.org/native_data_types/lists.html#odbchelper.list.slice 
    649649    for an introduction. 
    650      
     650 
    651651``slugify`` 
    652652    Converts to lowercase, removes non-alpha chars and converts spaces to hyphens 
    653      
     653 
    654654``stringformat`` 
    655655    Formats the variable according to the argument, a string formatting specifier. 
    656656    This specifier uses Python string formating syntax, with the exception that 
    657657    the leading "%" is dropped. 
    658      
     658 
    659659    See http://docs.python.org/lib/typesseq-strings.html for documentation 
    660660    of Python string formatting 
    661      
     661 
    662662``striptags`` 
    663663    Strips all [X]HTML tags 
    664      
     664 
    665665``time`` 
    666666    Formats a time according to the given format (same as the ``now`` tag). 
    667      
     667 
    668668``timesince`` 
    669669    Formats a date as the time since that date (i.e. "4 days, 6 hours") 
    670      
     670 
    671671``title`` 
    672672    Converts a string into titlecase 
    673      
     673 
    674674``truncatewords`` 
    675675    Truncates a string after a certain number of words 
    676      
     676 
    677677    **Argument:** Number of words to truncate after 
    678      
     678 
    679679``unordered_list`` 
    680680    Recursively takes a self-nested list and returns an HTML unordered list -- 
    681681    WITHOUT opening and closing <ul> tags. 
    682      
     682 
    683683    The list is assumed to be in the proper format. For example, if ``var`` contains 
    684684    ``['States', [['Kansas', [['Lawrence', []], ['Topeka', []]]], ['Illinois', []]]]``, 
    685685    then ``{{ var|unordered_list }}`` would return:: 
    686      
     686 
    687687        <li>States 
    688688        <ul> 
     
    696696        </ul> 
    697697        </li> 
    698      
     698 
    699699``upper`` 
    700700    Converts a string into all uppercase 
    701      
     701 
    702702``urlencode`` 
    703703    Escapes a value for use in a URL 
    704      
     704 
    705705``urlize`` 
    706706    Converts URLs in plain text into clickable links 
    707      
     707 
    708708``urlizetrunc`` 
    709709    Converts URLs into clickable links, truncating URLs to the given character limit 
    710      
     710 
    711711    **Argument:** Length to truncate URLs to. 
    712      
     712 
    713713``wordcount`` 
    714714    Returns the number of words 
    715      
     715 
    716716``wordwrap`` 
    717717    Wraps words at specified line length 
    718      
     718 
    719719    **Argument:** number of words to wrap the text at. 
    720      
     720 
    721721``yesno`` 
    722722    Given a string mapping values for true, false and (optionally) None, 
    723723    returns one of those strings according to the value: 
    724      
     724 
    725725    ==========  ======================  ================================== 
    726726    Value       Argument                Outputs