This tag takes either on or off as an argument and that determines whether auto-escaping is in effect inside the block. The block is closed with an endautoescape ending tag. When auto-escaping is in effect, all variable content has HTML escaping applied to it before placing the result into the output but after any filters have been applied. This is equivalent to manually applying the escape filter to each variable.
Defines a block that can be overridden by child templates. See Template inheritance for more information. An optional note may be inserted in the first tag.
For example, this is useful when commenting out code for documenting why the code was disabled. Produces one of its arguments each time this tag is encountered. The first argument is produced on the first encounter, the second argument on the second encounter, and so forth.
Once all arguments are exhausted, the tag cycles to the first argument and produces it again. The first iteration produces HTML that refers to class row1 , the second to row2 , the third to row1 again, and so on for each iteration of the loop. You can use variables, too. For example, if you have two template variables, rowvalue1 and rowvalue2 , you can alternate between their values like this:. In some cases you might want to refer to the current value of a cycle without advancing to the next value.
If you want to move the cycle to the next value independently of the original cycle tag, you can use another cycle tag and specify the name of the variable. So, the following template:. You can use any number of values in a cycle tag, separated by spaces.
Values enclosed in single quotes ' or double quotes " are treated as string literals, while values without quotes are treated as template variables.
This could be a problem if you want to use the value in a nested loop or an included template. If you only want to declare the cycle but not produce the first value, you can add a silent keyword as the last keyword in the tag.
For example:. When the silent keyword is used on a cycle definition, the silence automatically applies to all subsequent uses of that specific cycle tag. Outputs a whole load of debugging information, including the current context and imported modules. A string argument may also be a relative path starting with. For example, assume the following directory structure:. In template. Filters the contents of the block through one or more filters. Multiple filters can be specified with pipes and filters can have arguments, just as in variable syntax.
Note that the block includes all the text between the filter and endfilter tags. The escape and safe filters are not acceptable arguments. Instead, use the autoescape tag to manage autoescaping for blocks of template code.
Loops over each item in an array, making the item available in a context variable. If you need to loop over a list of lists, you can unpack the values in each sublist into individual variables. For example, if your context contains a list of x,y coordinates called points , you could use the following to output the list of points:.
This can also be useful if you need to access the items in a dictionary. For example, if your context contained a dictionary data , the following would display the keys and values of the dictionary:. Keep in mind that for the dot operator, dictionary key lookup takes precedence over method lookup.
Therefore if the data dictionary contains a key named 'items' , data. Avoid adding keys that are named like dictionary methods if you want to use those methods in a template items , values , keys , etc.
Read more about the lookup order of the dot operator in the documentation of template variables. These clauses are optional. Use of both and and or clauses within the same tag is allowed, with and having higher precedence than or e.
Use of actual parentheses in the if tag is invalid syntax. If you need them to indicate precedence, you should use nested if tags.
Contained within. This operator is supported by many Python containers to test whether the given value is in the container. The following are some examples of how x in y will be interpreted:. Not contained within. This is the negation of the in operator. Negated object identity. Tests if two values are not the same object. This is the negation of the is operator. You can also use filters in the if expression. All of the above can be combined to form complex expressions. For such expressions, it can be important to know how the operators are grouped when the expression is evaluated - that is, the precedence rules.
The precedence of the operators, from lowest to highest, is as follows:. This follows Python exactly. So, for example, the following complex if tag:. If you need different precedence, you will need to use nested if tags. Sometimes that is better for clarity anyway, for the sake of those who do not know the precedence rules. For example, instead of using:. It has two possible uses.
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:. If given one or more variables, check whether any variable has changed. For example, the following shows the date every time it changes, while showing the hour if either the hour or the date has changed:. Loads a template and renders it with the current context. The template name can either be a variable or a hard-coded quoted string, in either single or double quotes.
The variable may also be any object with a render method that accepts a context. This allows you to reference a compiled Template in your context. An included template is rendered within the context of the template that includes it. This example produces the output "Hello, John! Context: variable person is set to "John" and variable greeting is set to "Hello". If you want to render the context only with the variables provided or even no variables at all , use the only option.
No other variables are available to the included template:. This means that there is no shared state between included templates — each include is a completely independent rendering process.
Blocks are evaluated before they are included. This means that a template that includes blocks from another will contain blocks that have already been evaluated and rendered - not blocks that can be overridden by, for example, an extending template.
For example, the following template would load all the tags and filters registered in somelibrary and otherlibrary located in package package :. You can also selectively load individual filters or tags from a library, using the from argument.
See Custom tag and filter libraries for more information. The arguments are:. Such string can contain format specifiers characters as described in the date filter section. The predefined formats may vary depending on the current locale and if Format localization is enabled, e. This complex tag is best illustrated by way of an example: say that cities is a list of cities represented by dictionaries containing "name" , "population" , and "country" keys:.
The following snippet of template code would accomplish this:. Group objects are instances of namedtuple with two fields:. Our example relies on the fact that the cities list was ordered by country in the first place. If the cities list did not order its members by country , the regrouping would naively display more than one group for a single country.
For example, say the cities list was set to this note that the countries are not grouped together :. The easiest solution to this gotcha is to make sure in your view code that the data is ordered according to how you want to display it. Library , takes a function that accepts any number of arguments, wraps it in a render function and the other necessary bits mentioned above and registers it with the template system.
Note that the first argument must be called context. For example:. Then in the template any number of arguments, separated by spaces, may be passed to the template tag. This is done by using the as argument followed by the variable name. Doing so enables you to output the content yourself where you see fit:.
Another common type of template tag is the type that displays some data by rendering another template. Writing inclusion tags is probably best demonstrated by example. First, define the function that takes the argument and produces a dictionary of data for the result. The important point here is we only need to return a dictionary, not anything more complex. This will be used as a template context for the template fragment.
This template is a fixed feature of the tag: the tag writer specifies it, not the template designer. Following our example, the template is very short:.
Following our example, if the above template is in a file called results. Alternatively it is possible to register the inclusion tag using a django. Template instance:. Sometimes, your inclusion tags might require a large number of arguments, making it a pain for template authors to pass in all the arguments and remember their order.
Note that the first parameter to the function must be called context. In that register. Then, any time you want to use that custom tag, load its library and call it without any arguments, like so:. It automatically gets access to the context. The template system works in a two-step process: compiling and rendering. To define a custom template tag, you specify how the compilation works and how the rendering works. Each node is an instance of django. Node and has a render method.
A compiled template is a list of Node objects. When you call render on a compiled template object, the template calls render on each Node in its node list, with the given context. The results are all concatenated together to form the output of the template. For each template tag the template parser encounters, it calls a Python function with the tag contents and the parser object itself. This function is responsible for returning a Node instance based on the contents of the tag.
The parser for this function should grab the parameter and create a Node object:. The second step in writing custom tags is to define a Node subclass that has a render method. Continuing the above example, we need to define CurrentTimeNode :. Ultimately, this decoupling of compilation and rendering results in an efficient template system, because a template can render multiple contexts without having to be parsed multiple times.
However, there are still a couple of things you should keep in mind when writing a template tag. When the variable is ultimately rendered, it will be affected by the auto-escape setting in effect at the time, so content that should be safe from further escaping needs to be marked as such. If we had neglected to pass in the current context. Once a node is parsed, its render method may be called any number of times.
Since Django is sometimes run in multi-threaded environments, a single node may be simultaneously rendering with different contexts in response to two separate requests. To make sure your template tags are thread safe, you should never store state information on the node itself.
A naive implementation of CycleNode might look something like this:. This is not what we want! The tag method takes two arguments:. Although you can pass any number of arguments to a template tag using token. This will allow the url tag to use a context variable as the value of the URL name to be reversed.
To use this library, add a load call at the top of any template using the url tag, and wrap the first argument to the url tag in quotes. The new library also drops support for the comma syntax for separating arguments to the url template tag. Existing templates be migrated to use the new syntax.
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. Caches a complex variable under a simpler name. This is useful when accessing an "expensive" method e.
If value is 4 , then the output will be 6. This filter will first try to coerce both values to integers. If this fails, it'll attempt to add the values together anyway. This will work on some data types strings, list, etc.
If it fails, the result will be an empty string. Strings that can be coerced to integers will be summed , not concatenated, as in the first example above. If value is "django" , the output will be "Django". If value is "Django" , the output will be " Django ". If value is "String with spaces" , the output will be "Stringwithspaces". The c and u format specification characters were added in Django 1.
If value is a datetime object e. Note that predefined formats may vary depending on the current locale. If value evaluates to False , use given default. Otherwise, use the value. If value is "" the empty string , the output will be nothing. If and only if value is None , use given default. Note that if an empty string is given, the default value will not be used. Use the default filter if you want to fallback for empty strings. If value is None , the output will be the string "nothing".
Takes a list of dictionaries and returns that list sorted in reverse order by the key given in the argument. This works exactly the same as the above filter, but the returned value will be in reverse order. Returns True if the value is divisible by the argument. If value is 21 , the output would be True. The escaping is only applied when the string is output, so it does not matter where in a chained sequence of filters you put escape : it will always be applied as though it were the last filter.
Applying escape to a variable that would normally have auto-escaping applied to the result will only result in one round of escaping being done. So it is safe to use this function even in auto-escaping environments. Escapes characters for use in JavaScript strings. Format the value like a 'human-readable' file size i.
If value is , the output would be If value is the list ['a', 'b', 'c'] , the output will be 'a'. This is rarely useful as ampersands are automatically escaped. See escape for more information.
When used without an argument, rounds a floating-point number to one decimal place -- but only if there's a decimal part to be displayed. If used with a numeric integer argument, floatformat rounds a number to that many decimal places. If the argument passed to floatformat is negative, it will round a number to that many decimal places -- but only if there's a decimal part to be displayed.
Using floatformat with no argument is equivalent to using floatformat with an argument of Applies HTML escaping to a string see the escape filter for details. This filter is applied immediately and returns a new, escaped string. This is useful in the rare cases where you need multiple escaping or want to apply other filters to the escaped results.
Normally, you want to use the escape filter. Given a whole number, returns the requested digit, 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. If value is , the output will be 8. It's safe to use this filter on a string that has already gone through the urlencode filter. If value is "? Joins a list with a string, like Python's str.
If value is the list ['a', 'b', 'c', 'd'] , the output will be the string "d". If value is ['a', 'b', 'c', 'd'] , the output will be 4.
Returns True if the value's length is the argument, or False otherwise. If value is ['a', 'b', 'c', 'd'] , the output will be True. If value is Django , the output will be "Django ". Returns the value turned into a list. For a string, it's a list of characters. For an integer, the argument is cast into an unicode string before creating a list. If value is the string "Joel" , the output would be the list [u'J', u'o', u'e', u'l'].
If value is , the output will be the list [u'1', u'2', u'3']. Returns a plural suffix if the value is not 1. By default, this suffix is 's'. For words that require a suffix other than 's' , you can provide an alternate suffix as a parameter to the filter.
For words that don't pluralize by simple suffix, you can specify both a singular and plural suffix, separated by a comma. A wrapper around pprint. If value is the list ['a', 'b', 'c', 'd'] , the output could be "b". If value is Django , the output will be " Django". Marks a string as not requiring further HTML escaping prior to output. When autoescaping is off, this filter has no effect.
If you are chaining filters, a filter applied after safe can make the contents unsafe again. For example, the following code prints the variable as is, unescaped:. Applies the safe filter to each element of a sequence. Useful in conjunction with other filters that operate on sequences, such as join.
You couldn't use the safe filter directly in this case, as it would first convert the variable into a string, rather than working with the individual elements of the sequence. Uses the same syntax as Python's list slicing. Converts to lowercase, removes non-word characters alphanumerics and underscores and converts spaces to hyphens. Also strips leading and trailing whitespace. If value is "Joel is a slug" , the output will be "joel-is-a-slug".
Formats the variable according to the argument, a string formatting specifier. If value is "Joel is a slug" , the output will be "Joel is a slug". Note that the predefined format is locale-dependant.
0コメント