Getting Started with Django: templates

Source: Internet
Author: User
Tags html tags urlencode

"Reprint" One, variable

1. The form of a variable is: {{variable}}, when the template engine encounters a variable, the engine uses the value of the variable instead of the variable.
2. Use dot (.) The ability to access a variable's properties
3. What is the order of the search when the template engine touches the dot?
    A. Dictionary lookup, for example: foo["var1"]
    B. Property lookup, for example: Foo.bar
    C. Method Lookup, for example: Foo.bar ()
    D.list-index lookup, for example, Foo[bar]

Note: Method lookup is more complex than General lookup
(1) If the method throws an exception during the call to the method, the exception will occur unless the exception object has a property silent_variable_failure,
If this value is true, an empty string will be returned.
(2) method calls are only valid for methods that have no parameters
(3) Some methods can have side effects, so the system allows the method to set a property alters_data, and if the value is true, then it is not possible to call the
The method is set up by:
def sensitive_function (self):
#函数内容
Sensitive_function.alters_data = True
4. If a variable used in the template does not exist, the template system replaces the value of the variable template_string_if_invalid in setting.py, by default, the value of the variable is ". Second, filter

1. The filter can be used to modify the display of the variable, the form of the filter is: {{variable | filter}}, pipe symbol ' | ' The representative uses the filter 2. Filters can be used in a chained way, for example: {{text | escape | linebreaks}} 3. Filters can also take parameters, such as: {{bio|truncatewords:30}} 4. In the parameters of the filter, if there are spaces, then It needs to be enclosed in quotes, such as: {{list | join: ","} 5.django 30 built-in filters (1) Add is used in the form of: {{value |
    Add: 2 "}} Meaning: Increase value by 2 (2) addslashes using the form: {{value | addslashes}} meaning: Add a backslash before quotation marks in value (3) Capfirst use form: {{value | capfirst}} meaning: The first character of value is converted to uppercase (4) cut is used in the form of: {{value | cut:a RG}}, for example, if value is "String with spaces" Arg is "" then the output is "stringwithspaces" meaning: Remove the value of all arg from the given value (5) Date makes In the form:: (a) {{value | date: ' d d M Y '}}, for example, if value is a DateTime object (Datetime.datetime.now ()) then the output will be a string "Wed
         2008 "(b) {{value |}}}, this form does not format a string, at which point the formatted string automatically takes the form set by the Date_format. Significance: Output date format data in a given format (6) Default use form: {{value | default: ' Nothing '}, for example, if value is "", then the output will be no meaning: If the meaning of value is false, thenThe output uses the default value (7) Default_if_none use form: {{value | default_if_none: ' Nothing '}}, for example, if value is none, then the output will be nothing Meaning: If value is none, then the output will use the default value (8) dictsort meaning: If value is a dictionary, the return value is in the form of a keyword-sorted result: {{value | dictsort : "Name"}, for example, if value is: [{' Name ': ' Zed ', ' Age ':}, {' name ': ' Amy ', ' Age ':}, {' Name ' : ' Joe ', ' Age ': 31},] Then, the output is: [{' Name ': ' Amy ', ' Age ':}, {' name ': ' Joe ', ' Age ': '} ', {' n
Ame ': ' Zed ', ' age ': {},] (9) dictsortreversed meaning: If value is a dictionary, then the return value is in the form of the reverse order of the result ordered by the keyword: identical to (8) above. (a) Divisibleby use form: {{value | divisibleby:arg}}, if value is 21,arg is 3, then the output will be true: if value can be divisible by ARG, then the return value will be true (one) ESC
    Ape Use form: {{value | escape}} meaning: Replace some characters in value to fit in HTML format, including: < is converted to &lt;
    > is converted to &gt;
    ' (single quote) are converted to & #39;
    "(double quote) is converted to &quot;

   & is converted to &amp; Escape only inOutput, so the escape is not enough to be in the middle of a chain filter,
 

He should always be the last filter, and if you want to use it in the middle of a chain filter, you can use the Force_escape

(Escapejs)
   use form: {{value | escapejs}}
   meaning: Replace some characters in value to accommodate JavaScript and JSON formatting.
(filesizeformat)
   use form: {{value | filesizeformat}}
   Significance: Format value to make it readable file size, such as 13KB,4.1MB, etc.
(s)
   First Use form: {{value | ' s
   .} meaning: Returns the number one item in the list, for example, if value is a list [' A ', ' B ', ' C '], then the output will be ' a '.
(Floatformat)
   using the form: {{value | floatformat}} or {{Value|floatformat:arg}},
             arg can be positive or negative. Floatformat that have no parameters are equivalent to Floatformat:-1
   (1) If you do not have ARG, the engine is rounded up with a maximum of one decimal.

34.23234 {{Value|floatformat}}} 34.2
34.00000 {{Value|floatformat}}} 34
34.26000 {{Value|floatformat}}} 34.3
(2) If ARG is a positive number, the engine is rounded and retains the decimal number of arg digits.
34.23234 {{value|floatformat:3}}} 34.232
34.00000 {{value|floatformat:3}}} 34.000
34.26000 {{value|floatformat:3}}} 34.260
(3) If ARG is a negative number, then the engine is rounded up, and if there is a fractional part, then the ARG decimal is retained, otherwise there is no decimal part.
34.23234 {{value|floatformat: "-3"}} 34.232
34.00000 {{value|floatformat: "-3"}} 34
34.26000 {{value|floatformat: "-3"}} 34.26
(Get_digit)
Use form: {{value | get_digit: ' arg '}}, for example, if value is 123456789,arg is 2, then output is 8
Meaning: Given a number, return, the requested number, remember: 1 represents the rightmost number, if value is not a valid input,
Then all the original values are returned.
(Iriencode)
Use form: {{value | iriencode}}
Meaning: If value has non-ASCII characters, then it is scratched into the appropriate encoding in the URL, if value has been urlencode,
The operation will no longer work.
() Join
Use form: {{value | join: ' ARG '}}, if value is [' A ', ' B ', ' C '],arg is '//' then the output is a//b//c
Meaning: Joins a list using the specified string, acting like Python's str.join (list)
(a) Last
Use form: {{value | last}}
Meaning: Returns the last item in the list
(length)
Use form: {{value | length}}
Meaning: Returns the length of value.
(length_is)
Use form: {{value | length_is: ' ARG '}}
Meaning: Returns True if the length of value equals arg, for example: if value is [' A ', ' B ', ' C '],arg is 3, then returns True
(linebreaks)
Use form: {{Value|linebreaks}}
Meaning: "\ n" in value will be
Overrides, and the entire value is surrounded by use, thus adapting and HTML format
(LINEBREAKSBR)
Use form: {{value |LINEBREAKSBR}}
Meaning: "\ n" in value will be
Alternative
(linenumbers)
Use form: {{value | linenumbers}}
Meaning: The text displayed, with the number of lines.
(Ljust)
Use form: {{value | ljust}}
Meaning: In a field of a given width, the left alignment displays value
(m) Center
Use form: {{value | center}}
Meaning: In a field of a given width, the center alignment displays value
(Rjust)
Use form: {{value | rjust}}
Meaning: In a field of a given width, the right alignment displays value
(num) lower
Use form: {{value | lower}}
Meaning: Converts a string to a lowercase form
(make_list)
Use form: {{value | make_list}}
Meaning: Converts value to a list, to a string, to a list of characters, to integers, to an integer list
For example, value is Joel, then the output will be [u ' J ', u ' o ', U ' e ', U ' l '];value is 123, then the output will be [1,2,3]
(pluralize)
Use form: {{value | pluralize}}, or {{value | pluralize: ' ES '}}, or {{value | pluralize: ' y,ies '}}
Meaning: If value is not 1, a plural suffix is returned, and the default suffix is ' s '
(random)
Use form: {{value | random}}
Meaning: Returns an arbitrary item from a given list
(removetags)
Use form: {{value | removetags: "TAG1 tag2 tag3 ..."}
Meaning: Deletes the label of Tag1,tag2 ... in value. For example, if value isJoelis a slug
tags is "b span", then the output will be: "Joel is a slug
(in) safe
Use form: {{value | safe}}
Meaning: When the system is set autoescaping open, the filter makes the output not escape conversion
(SAFESEQ)
Basically the same as the above safe, but one difference is that safe is for strings, and SAFESEQ is for multiple strings sequence
(Slice)
Use form: {{some_list | slice: ': 2 '}}
Meaning: The same as the slice in the Python syntax: 2 represents the second element of the first
(slugify)
Use form: {{value | slugify}}
Meaning: Converts value to lowercase, the colleague deletes all the word characters, and the spaces into horizontal lines
For example, if value is an slug of the Joel is, then the output will be Joel-is-a-slug
(km) STRINGFORMAT
This doesn't work very often.
(striptags)
Use form: {{value | striptags}}
Meaning: Deletes all HTML tags in value
(Panax) Time
Use form: {{value | time: ' H:I '}} or {{value | time}}
Meaning: Format the time output, and if no formatting parameters are followed by, the output is set in Time_format.
(a) Title
Converts a string into the title format.
(truncatewords)
Use form: {{value | truncatewords:2}}
Meaning: Cut value into truncatewords the specified number of words
For example, if value is an Joel is a slug then the output will be: "Joel is ..."
(truncatewords_html)
Use the same form (39)
Significance: If a label is turned on before the truncation point, it will be closed immediately at the truncation point.
Because this operation is less efficient than truncatewords, all is considered for use only when value is in HTML format.
(upper)
Converts a string to uppercase
(UrlEncode)
To UrlEncode a string
(urlize)
Meaning: Converts a URL in a string into a clickable form.
Use form: {{value | urlize}}
For example, if value is a check out www.djangoproject.com, then the output will be:
Check out www.djangoproject.com
(Urlizetrunc)
Use form: {{value | urlizetrunc:15}}
Meaning: Same as (43), but there is a difference is that the actual link character will be truncate into a specific length, followed by ... Reality.
(WordCount)
Returns the number of words in a string
(WordWrap)
Use form: {{value | wordwrap:5}}
Meaning: Wraps a string according to the specified length
For example, if value is the Joel is a slug, then the output will be:
Joel
is a
Slug
(timesince)
Use form: {{value | timesince:arg}}
Meaning: Returns the number of days and hours of argument arg to value
For example, if Blog_date is a date instance that represents midnight 2006-06-01, and Comment_date is a date instance representing 8 in the morning of 2006-06-01,
Then {{Comment_date|timesince:blog_date}} will return "8 hours".
(Timeuntil)
Use form: {{value | timeuntil}}
Meaning: Basically the same as (47), a different point is that the value is returned by the number of days and hours from the current date.Third, the label

1. The form of the label is: {% tag%}, the label is more complex than the variable 2. The role of the label (1) Create some text (2) in the output by executing loops and some logic to implement the control flow (3) load some external information into the template 3. Built-in label (1) Autoescape In the form: {% autoescape off%} (content) {% Endautoescape%} meaning: When a piece of content does not need to be automatically escaped, so write it.
  Of course, if you need to escape some parts of the block, call filter can also. (2) block use form: {% block%} (definition chunk content) {% Endblock%} meaning: Define a chunk that can be inherited by his descendants template rewrite (3) C
  Omment use form: {% comment%} (content) {% endcomment%} meaning: The template system ignores all content inside the label. (4) Cycle use form: For example: <tr class= "{% cycle list%}" > ... </tr> significance: rotate in cycles

  Use the value from the given list of strings.
     (5) Extends use form: {% extends "base.html"%} or {% extends variable%} variable can be a string or a template object.
  Meaning: Indicates that this template is to be extended to the specified parent template. (6) Filter Use form: {%filter force_escape|lower%} (content) {%endfilter%} meaning: The filter label to delimit the
  The content performs the filter operation.               (7) Firstof use form: {%firstof var1 var2 var3%} meaning: The output of a variable with the first value not equal to False is equivalent to:
     {% if var1%}
     {{var1}}}
         {% Else%}
             {% if var2%}
         {{VAR2}}}
             {% Else%}
                 {% if var3%}
             {{VAR3}}}
         {% ENDIF%}
     {% ENDIF%}
  {% ENDIF%} (8) For use form: {% for variable in list/dict%} (using variable) {% endfor%} meaning: Loop list Note: (a) can also reverse traverse {% for variable in list/dict reversed%} (b) can also be {% for x, y in points%} points Each element of (X,y) (c) can also {% for key,value in data.items%} data is a dictionary for loop defined in some of the built-in variable Forloop.
     Counter the current number of iterators (starting from 1) Forloop.counter0 the current number of iterators (starting at 0) Forloop.revcounter the current number of reverse iterators (starting from 1)            Forloop.revcounter0 the current number of reverse iterators (starting with 0) Forloop.first value is true if it is the first time through an iterator forloop.last Value is true, if the last time the iterator Forloop.parentloop for a nested loop, this is the upper loop of the current loop (9) for ... empty uses the following form: {% for Varib
          Ale in list%}    (Content 1)
              {% EMPTY%}
         (Content 2)
  {% endfor%} meaning: When the list is empty, the ability to execute content 2, which is the same as the first if to determine whether the list exists, and then what to do according to the situation. The If use form is as follows: {% if variable%} (content 1) {% Else%} (content 2) {% Endi F%} Note: You can use and or or not in variable, but one must remember that you do not allow and and or use the form of (a) ifchanged: (a) If the cyclic variable is detected directly, then Use: {% ifchanged%} (content) {% endifchanged%} (b) If you detect a dot variable of a loop variable, such as a loop variable that is date, then detect Date.hour, then use: {% ifchanged date.hour%} (content) {% endifchanged%} (c) ifchange 
   D can also add a {% else%} statement meaning: Detecting the value of this loop is not the same as the value of the previous loop, but only within the loop.
          () ifequal use form: {% ifequal variable1 variable2%} ...
   {% endifequal%} significance: Determines whether two variables are equal. (12) Ifnotequal uses the same form as: {% include "foo/bar.html"%} or {% include template_name%} meaning Righteousness: Adds the contents of another template file to the file.
   Note that the difference extend is inherited.
 (a) Now     Use form: {% now "JS F Y h:i"%}, note that there are situations that need to be escaped such as {% now "JS o\f F"%}, because F is a format string
 
attached: The specific format string is shown below

A ' a.m. ' or ' p.m. ' (this is slightly different than PHP's output, because this includes periods to match Associa Ted Press style.) ' A.M. '
A ' AM ' or ' PM '. ' AM '
b Month, textual, 3 letters, lowercase. ' A few '
B not implemented.
D Day of the month, 2 digits with leading zeros. ' 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. ' To ' 12 '
H Hour, 24-hour format. ' To ' 23 '
I Minutes. ' 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. ' To ' 12 '
M Month, textual, 3 letters. ' A few '
n Month without leading zeros. ' 1 ' to ' 12 '
N Month abbreviation in Associated Press style. Proprietary extension. ' 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-if they ' re zero and Special-case strings ' m Idnight ' and ' noon ' if appropriate. Proprietary extension. ' 1 a.m. ', ' 1:30 p.m. ', ' Midnight ', ' noon ', ' 12:30 p.m. '
R RFC 2822 formatted date. ' Thu, Dec 2000 16:01:07+0200 '
s Seconds, 2 digits with leading zeros. ' To ' 59 '
S 中文版 ordinal suffix for day of the month, 2 characters. ' St ', ' nd ', ' rd ' or ' th '
T number of days in the given month. to 31
T time Zone of the 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, 53
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 to those east of UTC is always positive.
(spaceless)
Use form: {% spaceless%}
Content
{% endspaceless%}
Meaning: Deletes all tab or carriage return characters in the enclosing content.
(template)
Use form: {% Templatetag%}
Meaning: The template system itself has no escaping concept, so if you want to output a thing like "{%", you need to take this approach, or you will have a syntax error
The parameters are:
Openblock {%
Closeblock%}
openvariable {{
Closevariable}}
Openbrace {
Closebrace}
opencomment {#
Closecomment #}
(a) with
Use form:
{% with "expensive var1" as var2%}
{% Endwith%}
Meaning: When a variable's access consumes a large template resolution, it can be replaced with a different variable, which is only valid with internal.
() URL
Use form: {% URL path.to.some_view arg1,arg2%}
Meaning: Given the name of a function in a module, given a parameter, the template engine gives you a URL to avoid hard-coded URLs into the code

 Note: The prerequisite is that there is a mapping in the urlconf, and if the mapping is not in urlconf, an exception is thrown, which is optionally using the {% URL Path.to.view arg1, arg2 as The URL%} <a href= "{{the_url}}" >link to optional stuff</a> actually this is equivalent to {% URL P Ath.to.view as The_url%} {% if The_url%} <a href= ' {{the_url}} ' >link to optional stuff& lt;/a> {% endif%} 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.