Danjgo study notes (five) ---- common template filters and homemade filter

danjgo template filters and custom filters

# Django template filters notes:

Why ## need filters?
Because DTL is not supported function calls of `()` and therefore can not pass parameters to a function, which will have significant limitations. The filter is actually a function that can be processed parameters need to be addressed, and may also receive one additional parameter (that is, at most only two parameters).

## add filter :
the parameters passed in the value added to the original top. This filter will attempt to `` parameter value `` and then converted into the plastic is added. If the conversion process fails to shaping, and then will `` `parameters' values splicing. If a string, then the string will be spliced into, if it is a list, it will splice into a list. Sample code is as follows:

```python
{{ value|add:"2" }}
```

If `value` is equal to 4, then the result will be 6. If `value` is equal to a normal string, such as` abc`, the result will be `abc2`. `Add` filter source code is as follows:

```python
def add(value, arg):
"""Add the arg to the value."""
try:
return int(value) + int(arg)
except (ValueError, TypeError):
try:
return value + arg
except Exception:
return ''
```

 

## cut filter :
remove all specified string value. Similar to `` replace python` in (args, "") `. Sample code is as follows:

```python
{{ value|cut:" " }}
```

`Value` above example will remove all space characters. `Cut` filter source code is as follows:

```python
def cut(value, arg):
"""Remove all values of arg from the given string."""
safe = isinstance(value, SafeData)
value = value.replace(arg, '')
if safe and arg != ';':
return mark_safe(value)
return value
```

## `date` filter :
the
one date in the specified format, formatted into a string. Sample code is as follows:

Python `` `
# data
context = {
" Birthday ": DateTime.Now ()
}

# 模版
{{ birthday|date:"Y/m/d" }}
```

Then the output will be `2018/02 / 01`. `Y` which represents the four-digit year,` m` represents the two-digit month, `d` represents the two-digit day.
There is more time formatted. The table below.

| Character Format Description | exemplary |
| --- | --- | --- |
| the Y | four-digit year | 2018 |
| m | two-digit month | 01-12 |
| n-| month, 1-9 is not a prefix in front of 0 | 1-12 |
| D | two digit day | 01-31 |
| J | days, but no front 1-9 prefix 0 | 1-31 |
| G | h, 12 h format without prefix 1-9 0 foregoing | 1-12 |
| H | hour, 12-hour format, prefix 1-9 0 foregoing | 01-12 |
| G | hour, 24-hour format, 1-9 without a preceding prefix 0 | 1-23 |
| H | hour, 24-hour format, with a 0 prefix in front of 1-9 | 01-23 |
| I | min 1-9 0 prefix in front of | 00-59 |
| S | seconds, 1-9 in front of the prefix 0 | 00-59 |


#
## default

If the value is evaluated as `False`. For example `[]`, `" "`, `None`,` {} `` False` other such as in the `if` determination value` default` will use the default values ​​provided by the filter. Sample code is as follows:

```python
{{ value|default:"nothing" }}
```

If `value` is equal to an empty string. For example, `" "` then the above code will output `nothing`.

### default\_if\_none

If the value is `None`, it will use the default` default_if_none` provided. And `default` this distinction,` default` all been assessed as `False` will use the default value. The `default_if_none` only this value is equal to` None` time will use the default value. Sample code is as follows:

```python
{{ value|default_if_none:"nothing" }}
```

If `` value` is equal to "" `That is an empty string, then the output will be more than an empty string. If `value` is a` None` value, the above code will output `nothing`.

 

### first

Returns the first element of the list / tuple / string. Sample code is as follows:

```python
{{ value|first }}
```

If `value` is equal to` [ 'a', 'b', 'c'] `, then the output will be` a`.

 

### last

Returns the last element of the list / tuple / string. Sample code is as follows:

```python
{{ value|last }}
```

If `value` is equal to` [ 'a', 'b', 'c'] `, then the output will be` c`.

 

### floatformat

Use a rounded way to format floating point type. If the filter does not pass any parameters. Then only one decimal after the decimal point, if behind the decimal are all 0, then only reserved integer. Of course, also pass a parameter to identify a specific reserve several decimals.

1. If no arguments are passed:

| Value | stencil Code | output |
| --- | --- | --- |
| 34.23234 | `{{value \ |}} floatformat` | 34.2 |
| 34.000 | `{{value \ |}}` floatformat | 34 is |
| 34.260 | `{{value \ |}} floatformat` | 34.3 |

2. If the arguments:

| Value | stencil Code | output |
| --- | --- | --- |
| 34.23234 | `{{value \ | floatformat:`. 3}} | 34.232 |
| 34.0000 | `{{value \ | floatformat: }} `. 3 | 34.000 |
| 34.26000 |` {{value \ | floatformat: `. 3}} | 34.260 |

 

### join

Similar to the `Python`` join`, list / tuple / spliced ​​with the specified string of characters. Sample code is as follows:

```python
{{ value|join:"/" }}
```

If `value` is equal to` [ 'a', 'b', 'c'] `, then the output of the above code` a / b / c`.

 

### length

Get a list / tuple / string / length dictionary. Sample code is as follows:

```python
{{ value|length }}
```

If `value` is equal to` [ 'a', 'b', 'c'] `, 'then the output code above 3`. If `value` is` None`, then the above will return `0`.

 

### lower

The value of all the characters are converted to all lowercase. Sample code is as follows:

```python
{{ value|lower }}
```

If `value` is equal to` Hello World`. Then the above code outputs `hello world`.

 

### upper

Similar to the `lower`, just all the specified string converted to uppercase.

 

### random

Being a random list / string / select a value tuples. Sample code is as follows:

```python
{{ value|random }}
```

If `value` is equal to` [ 'a', 'b', 'c'] `, then randomly selects one or more code in the list.

 

### safe

Mark a string is safe. That will turn off automatically escapes the string. Sample code is as follows:

```python
{{value|safe}}
```

If `value` is a string that does not contain any special characters, such as` <a> `this, the above code will be the normal input string. If `value` is a string of` html` code, then the above code will put this `html` code is rendered to the browser.

 

### slice

`Sections similar in operation Python`. Sample code is as follows:

```python
{{ some_list|slice:"2:" }}
```

The above code will from `2` to` some_list` started slicing operation.

 

### stringtags

Remove all `html` label string. Sample code is as follows:

```python
{{ value|striptags }}
```

If `value` is` <strong> hello world </ strong> `, the above code will then output` hello world`.

### truncatechars

If the given string is longer than the length specified by the filter. Then it will be cut and spliced ​​three points will be used as an ellipsis. Sample code is as follows:

```python
{{ value|truncatechars:5 }}
```

If `value` is equal to ~` `Welcome to Beijing, then the resulting output is` `Beijing .... You may be thinking, why does not `` Beijing welcomes you ... it. Because the three points also accounted for three characters, so `` Beijing + character length of three points is 5.

 

### truncatechars\_html

Similar to the `truncatechars`, just will not cut` html` label. Sample code is as follows:

```python
{{ value|truncatechars:5 }}
```

If `value` is equal to` <p> Welcome to Beijing ~ </ p> `, the output will be` <p> Beijing ... </ p> `.

 

 

# Custom filters Notes :
1. First in an app, create a python package called `templatetags`, note the name of the package must be` templatetags`, otherwise they can not find.
2. In this package `templatetags` below, creates a file for storing filter python.
3. python in the new file, define the filter (i.e. function), the first parameter to this function is always the filtered value, and if the parameters passed when using filters, it can also define another parameter. But the filters can only have a maximum of two parameters.
4. After writing the filters (functions), use `django.template.Library.filter` register.
5. would also like to add this filter is located to the `settings.INSTALLED_APS` in this app, or Django can not find this filter.
6. `load` python package label loaded filter is located in the template.
7. The use of filters.
8. `django.template.Library.filter` can also be used as a decorator. If `filter` function does not pass any parameters, it will use this name to function as a filter name. Of course, if you do not want to use the function name as the filter name, you can also pass a `name` parameter. Sample code is as follows:``
`Python
@ register.filter ( 'my_greet')
DEF the greet (value, Word):
return value Word +
` ``

Guess you like

Origin www.cnblogs.com/xifengqidama/p/11347193.html