Etiket cetakan dan penyaring siap-pakai

This document describes Django's built-in template tags and filters. It is recommended that you use the automatic documentation, if available, as this will also include documentation for any custom tags or filters installed.

Acuan etiket siap-pakai

autoescape

Controls the current auto-escaping behavior. 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.

The only exceptions are variables that are already marked as "safe" from escaping, either by the code that populated the variable, or because it has had the safe or escape filters applied.

Contoh penggunaan:

{% autoescape on %}
    {{ body }}
{% endautoescape %}

block

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

comment

Ignores everything between {% comment %} and {% endcomment %}. 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.

Contoh penggunaan:

<p>Rendered text with {{ pub_date|date:"c" }}</p>
{% comment "Optional note" %}
    <p>Commented out text with {{ create_date|date:"c" }}</p>
{% endcomment %}

Etiket comment tidak dapat bersarang.

csrf_token

This tag is used for CSRF protection, as described in the documentation for Cross Site Request Forgeries.

cycle

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.

Etiket ini khususnya berguna dalam lingkaran:

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

Perulangan pertama menghasilkan HTML yang mengacu pada kelas row1, kedua pada row2, ketiga pada row1 kembali, dan seterusnya untuk setiap perulangan dari putaran.

You can use variables, too. For example, if you have two template variables, rowvalue1 and rowvalue2, you can alternate between their values like this:

{% for o in some_list %}
    <tr class="{% cycle rowvalue1 rowvalue2 %}">
        ...
    </tr>
{% endfor %}

Variabel-variabel disertakan dalam siklus akan diloloskan. Anda dapat meniadakan pelolosan-otomatis:

{% for o in some_list %}
    <tr class="{% autoescape off %}{% cycle rowvalue1 rowvalue2 %}{% endautoescape %}">
        ...
    </tr>
{% endfor %}

Anda dapat mencampur variabel dan string:

{% for o in some_list %}
    <tr class="{% cycle 'row1' rowvalue2 'row3' %}">
        ...
    </tr>
{% endfor %}

In some cases you might want to refer to the current value of a cycle without advancing to the next value. To do this, just give the {% cycle %} tag a name, using "as", like this:

{% cycle 'row1' 'row2' as rowcolors %}

From then on, you can insert the current value of the cycle wherever you'd like in your template by referencing the cycle name as a context variable. 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:

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

akan mengeluarkan:

<tr>
    <td class="row1">...</td>
    <td class="row1">...</td>
</tr>
<tr>
    <td class="row2">...</td>
    <td class="row2">...</td>
</tr>

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.

By default, when you use the as keyword with the cycle tag, the usage of {% cycle %} that initiates the cycle will itself produce the first value in the cycle. 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:

{% for obj in some_list %}
    {% cycle 'row1' 'row2' as rowcolors silent %}
    <tr class="{{ rowcolors }}">{% include "subtemplate.html" %}</tr>
{% endfor %}

This will output a list of <tr> elements with class alternating between row1 and row2. The subtemplate will have access to rowcolors in its context and the value will match the class of the <tr> that encloses it. If the silent keyword were to be omitted, row1 and row2 would be emitted as normal text, outside the <tr> element.

When the silent keyword is used on a cycle definition, the silence automatically applies to all subsequent uses of that specific cycle tag. The following template would output nothing, even though the second call to {% cycle %} doesn't specify silent:

{% cycle 'row1' 'row2' as rowcolors silent %}
{% cycle rowcolors %}

Anda dapat menggunakan etiket resetcycle untuk membuat sebuah etiket {% cycle %} mulai ulang dari nilai pertamanya ketika itu selanjutnya ditemui.

debug

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

extends

Sinyal-sinyal yang cetakan ini memperpanjang cetakan induk.

Etiket ini dapat digunakan dalam dua cara:

  • {% 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.

Lihat Template inheritance untuk informasi lebih.

Normally the template name is relative to the template loader's root directory. A string argument may also be a relative path starting with ./ or ../. For example, assume the following directory structure:

dir1/
    template.html
    base2.html
    my/
        base3.html
base1.html

Dalam template.html, jalur berikut akan sah:

{% extends "./base2.html" %}
{% extends "../base1.html" %}
{% extends "./my/base3.html" %}

filter

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.

Catat bahwa blok menyertakan semua teks diantara etiket filter dan endfilter.

Contoh penggunaan:

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

Catatan

The escape and safe filters are not acceptable arguments. Instead, use the autoescape tag to manage autoescaping for blocks of template code.

firstof

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

Contoh penggunaan:

{% firstof var1 var2 var3 %}

Ini adalah setara pada:

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

You can also use a literal string as a fallback value in case all passed variables are False:

{% firstof var1 var2 var3 "fallback value" %}

This tag auto-escapes variable values. You can disable auto-escaping with:

{% autoescape off %}
    {% firstof var1 var2 var3 "<strong>fallback value</strong>" %}
{% endautoescape %}

Atau jika hanya beberapa variabel harus diloloskan, anda dapat menggunakan:

{% firstof var1 var2|safe var3 "<strong>fallback value</strong>"|safe %}

You can use the syntax {% firstof var1 var2 var3 as value %} to store the output inside a variable.

for

Loops over each item in an array, making the item available in a context variable. For example, to display a list of athletes provided in athlete_list:

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

Anda dapat memutar kembali daftar dalam kebalikan dengan menggunakan {% for obj in list reversed %}.

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:

{% for x, y in points %}
    There is a point at {{ x }},{{ y }}
{% endfor %}

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:

{% for key, value in data.items %}
    {{ key }}: {{ value }}
{% endfor %}

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.items will return data['items'] instead of data.items(). 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.

Putaran for mensetel angka dari variabel-variabel tersedia dalam putaran.

Variabel Deskripsi
forloop.counter Perulangan saat ini dari putaran (indeks-1)
forloop.counter0 Perulangan saat ini dari putaran (indeks-0)
forloop.revcounter Jumlah perulangan dari akhir dari putaran (indeks-1)
forloop.revcounter0 Jumlah perulangan dari akhir dari perputaran (indeks-0)
forloop.first True jika ini adalah waktu pertama melalui perulangan
forloop.last True jika ini adalah waktu terakhir melalui perulangan
forloop.parentloop Untuk perulangan bersarang, ini adalah perulangan disekitar satu saat ini

for ... empty

The for tag can take an optional {% empty %} clause whose text is displayed if the given array is empty or could not be found:

<ul>
{% for athlete in athlete_list %}
    <li>{{ athlete.name }}</li>
{% empty %}
    <li>Sorry, no athletes in this list.</li>
{% endfor %}
</ul>

Diatas setara pada -- tetapi lebih pendek, lebih bersih, dan kemungkinan lebih cepat dari -- berikut:

<ul>
  {% if athlete_list %}
    {% for athlete in athlete_list %}
      <li>{{ athlete.name }}</li>
    {% endfor %}
  {% else %}
    <li>Sorry, no athletes in this list.</li>
  {% endif %}
</ul>

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 }}
{% elif athlete_in_locker_room_list %}
    Athletes should be out of the locker room soon!
{% 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 may take one or several {% elif %} clauses, as well as an {% else %} clause that will be displayed if all previous conditions fail. These clauses are optional.

Penghubung Boolean

Etiket if tags may use and, or or not to test a number of variables mungkin menggunakan and, or atau not untuk mencoba sejumlah variabel atau meniadakan variabel yang diberikan:

{% 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.
{% endif %}

{% if athlete_list and not coach_list %}
    There are some athletes and absolutely no coaches.
{% endif %}

Use of both and and or clauses within the same tag is allowed, with and having higher precedence than or e.g.:

{% if athlete_list and coach_list or cheerleader_list %}

akan diartikan seperti:

if (athlete_list and coach_list) or cheerleader_list

Use of actual parentheses in the if tag is invalid syntax. If you need them to indicate precedence, you should use nested if tags.

if etiket mungkin juga menggunakan penghubung ==, !=, <, >, <=, >=, in, not in, is, dan is not yang bekerja sebagai berikut:

Penghubung ==

Sama dengan. Contoh:

{% if somevar == "x" %}
  This appears if variable somevar equals the string "x"
{% endif %}
Penghubung !=

Tidak sama dengan. Contoh:

{% if somevar != "x" %}
  This appears if variable somevar does not equal the string "x",
  or if somevar is not found in the context
{% endif %}
Penghubung <

Kurang dari. Contoh:

{% if somevar < 100 %}
  This appears if variable somevar is less than 100.
{% endif %}
Penghubung >

Lebih besar dari. Contoh:

{% if somevar > 0 %}
  This appears if variable somevar is greater than 0.
{% endif %}
Penghubung <=

Kurang dari atau sama dengan. Contoh:

{% if somevar <= 100 %}
  This appears if variable somevar is less than 100 or equal to 100.
{% endif %}
Penghubung >=

Lebih besar atau sama dengan. Contoh:

{% if somevar >= 1 %}
  This appears if variable somevar is greater than 1 or equal to 1.
{% endif %}
Penghubung in

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:

{% if "bc" in "abcdef" %}
  This appears since "bc" is a substring of "abcdef"
{% endif %}

{% if "hello" in greetings %}
  If greetings is a list or set, one element of which is the string
  "hello", this will appear.
{% endif %}

{% if user in users %}
  If users is a QuerySet, this will appear if user is an
  instance that belongs to the QuerySet.
{% endif %}
Penghubung not in

Tidak terkandung dalam. Ini adalah lawan dari penghubung in.

penghubung is

Pencirian obyek. Coba jika dua nilai adalah obyek sama. Contoh:

{% if somevar is True %}
  This appears if and only if somevar is True.
{% endif %}

{% if somevar is None %}
  This appears if somevar is None, or if somevar is not found in the context.
{% endif %}
penghubung is not

Ditiadakan penciri obyek. Percobaan jika dua nilai bukan obyek sama. Ini adalah meniadakan dari penghubung is. Contoh:

{% if somevar is not True %}
  This appears if somevar is not True, or if somevar is not found in the
  context.
{% endif %}

{% if somevar is not None %}
  This appears if and only if somevar is not None.
{% endif %}

Filter

Anda dapat juga menggunakan penyaring dalam pernyataan if. Sebagai contoh:

{% if messages|length >= 100 %}
   You have lots of messages today!
{% endif %}

Pernyataan rumit

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:

  • or
  • and
  • not
  • in
  • ==, !=, <, >, <=, >=

(Ini mengikuti Python tepatnya). Jadi, sebagai contoh, etiket if rumit berikut:

{% if a == b or c == d and e %}

...akan diartikan sebagai:

(a == b) or ((c == d) and e)

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.

The comparison operators cannot be 'chained' like in Python or in mathematical notation. For example, instead of using:

{% if a > b > c %}  (WRONG)

anda harus menggunakan:

{% if a > b and b > c %}

ifequal dan ifnotequal

{% ifequal a b %} ... {% endifequal %} adalah cara mutlak menulis {% if a == b %} ... {% endif %}. Juga, {% ifnotequal a b %} ... {% endifnotequal %} digantikan oleh {% if a != b %} ... {% endif %}. Etiket ifequal dan ifnotequal akan diusangkan dalam terbitan mendatang.

ifchanged

Periksa jika nilai telah berubah dari putaran terakhir dari perulangan.

Etiket blok {% ifchanged %} digunakan dalam perulangan. Itu mempunyai dua kemungkinan penggunaan.

  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. 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:

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

The ifchanged tag can also take an optional {% else %} clause that will be displayed if the value has not changed:

{% for match in matches %}
    <div style="background-color:
        {% ifchanged match.ballot_id %}
            {% cycle "red" "blue" %}
        {% else %}
            gray
        {% endifchanged %}
    ">{{ match }}</div>
{% endfor %}

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.

Contoh ini menyertakan isi dari cetakan "foo/bar.html":

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

Normally the template name is relative to the template loader's root directory. A string argument may also be a relative path starting with ./ or ../ as described in the extends tag.

Contoh ini menyertakan isi dari cetakan yang namanya dikandung dalam variabel template_name:

{% include template_name %}

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!":

  • Konteks: variabel person``disetel menjadi ``"John" dan variabel greeting disetel menjadi "Hello".

  • Cetakan:

    {% include "name_snippet.html" %}
    
  • Cetakan name_snippet.html:

    {{ greeting }}, {{ person|default:"friend" }}!
    

Anda dapat melewatkan konteks tambahan pada cetakan menggunakan argumen-argumen kata kunci:

{% include "name_snippet.html" with person="Jane" greeting="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:

{% include "name_snippet.html" with greeting="Hi" only %}

Catatan

The include tag should be considered as an implementation of "render this subtemplate and include the HTML", not as "parse this subtemplate and include its contents as if it were part of the parent". 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.

load

Memuat kumpulan etiket cetakan penyesuaian.

For example, the following template would load all the tags and filters registered in somelibrary and otherlibrary located in package package:

{% load somelibrary package.otherlibrary %}

You can also selectively load individual filters or tags from a library, using the from argument. In this example, the template tags/filters named foo and bar will be loaded from somelibrary:

{% load foo bar from somelibrary %}

Lihat Custom tag and filter libraries untuk informasi lebih.

lorem

Menampilkan teks latin "lorem ipsum" acak. Ini berguna untuk menyediakan contoh data dalam cetakan.

Penggunaan:

{% lorem [count] [method] [random] %}

Etiket {% lorem %} dapat digunakan dengan nol, satu, dua atau tiga argumen. Argumennya adalah:

Argument Deskripsi
count Sejumlah (atau variabel) mengandung sejumlah paragraf atau kata-kata untuk membangkitkan (awalan adalah 1).
method Antara w untuk kata-kata, p untuk paragraf HTML atau b untuk blok-blok paragraf teks-polos (awalan b).
random Kata random, yang jika diberikan, tiadk menggunakan paragraf umum ("Lorem ipsum dolor sit amet...") ketika membangkitkan teks.

Contoh:

  • {% lorem %} akan mengeluarkan paragraf umum "lorem ipsum".
  • {% lorem 3 p %} akan mengeluarkan paragraf umum "lorem ipsum" dan dua paragraf acak masing-masing dibungkus daam etiket HTML <p>.
  • {% lorem 2 w random %} akan mengeluarkan dua kata Latin acak.

now

Displays the current date and/or time, using a format according to the given string. Such string can contain format specifiers characters as described in the date filter section.

Contoh:

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

Catat bahwa anda dapat meloloskan-garis-miring-terbalik sebuah bentuk string jika anda ingin menggunakan nilai "mentah". Dalam contoh ini, kedua "o" dan "f" adalah meloloskan-garis-miring-terbalik, karena sebaliknya setiapnya adalah bentuk string yang menampilkan tahun dan waktu, masing-masing:

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

Ini akan ditampilkan sebagai "It is the 4th of September".

Catatan

The format passed can also be one of the predefined ones DATE_FORMAT, DATETIME_FORMAT, SHORT_DATE_FORMAT or SHORT_DATETIME_FORMAT. The predefined formats may vary depending on the current locale and if Format localization is enabled, e.g.:

It is {% now "SHORT_DATETIME_FORMAT" %}

You can also use the syntax {% now "Y" as current_year %} to store the output (as a string) inside a variable. This is useful if you want to use {% now %} inside a template tag like blocktrans for example:

{% now "Y" as current_year %}
{% blocktrans %}Copyright {{ current_year }}{% endblocktrans %}

regroup

Regroups a list of alike objects by a common attribute.

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:

cities = [
    {'name': 'Mumbai', 'population': '19,000,000', 'country': 'India'},
    {'name': 'Calcutta', 'population': '15,000,000', 'country': 'India'},
    {'name': 'New York', 'population': '20,000,000', 'country': 'USA'},
    {'name': 'Chicago', 'population': '7,000,000', 'country': 'USA'},
    {'name': 'Tokyo', 'population': '33,000,000', 'country': 'Japan'},
]

...dan anda ingin menampilkan daftar susunan bertingkat yang diurutkan berdasarkan negara, seperti ini:

  • India
    • Mumbai: 19,000,000
    • Calcutta: 15,000,000
  • USA
    • New York: 20,000,000
    • Chicago: 7,000,000
  • Jepang
    • Tokyo: 33,000,000

You can use the {% regroup %} tag to group the list of cities by country. The following snippet of template code would accomplish this:

{% regroup cities by country as country_list %}

<ul>
{% for country in country_list %}
    <li>{{ country.grouper }}
    <ul>
        {% for city in country.list %}
          <li>{{ city.name }}: {{ city.population }}</li>
        {% endfor %}
    </ul>
    </li>
{% endfor %}
</ul>

Let's walk through this example. {% regroup %} takes three arguments: the list you want to regroup, the attribute to group by, and the name of the resulting list. Here, we're regrouping the cities list by the country attribute and calling the result country_list.

{% regroup %} produces a list (in this case, country_list) of group objects. Group objects are instances of namedtuple() with two fields:

  • grouper -- brang dikelompokkan berdasarkan (misalnya, string "India" atau "Japan").
  • list -- sebuah daftar dari semua barang dalam kelompok ini (misalnya, sebuah daftar dari semua kota dengan negara='India').

Karena {% regroup %} menghasilkan obyek-obyek namedtuple(), anda dapat juga menulis contoh sebelumnya sebagai:

{% regroup cities by country as country_list %}

<ul>
{% for country, local_cities in country_list %}
    <li>{{ country }}
    <ul>
        {% for city in local_cities %}
          <li>{{ city.name }}: {{ city.population }}</li>
        {% endfor %}
    </ul>
    </li>
{% endfor %}
</ul>

Note that {% regroup %} does not order its input! 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):

cities = [
    {'name': 'Mumbai', 'population': '19,000,000', 'country': 'India'},
    {'name': 'New York', 'population': '20,000,000', 'country': 'USA'},
    {'name': 'Calcutta', 'population': '15,000,000', 'country': 'India'},
    {'name': 'Chicago', 'population': '7,000,000', 'country': 'USA'},
    {'name': 'Tokyo', 'population': '33,000,000', 'country': 'Japan'},
]

Dengan masukan ini untuk cities, contoh kode cetakan {% regroup %} diatas akan menghasilkan keluaran berikut:

  • India
    • Mumbai: 19,000,000
  • USA
    • New York: 20,000,000
  • India
    • Calcutta: 15,000,000
  • USA
    • Chicago: 7,000,000
  • Jepang
    • Tokyo: 33,000,000

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.

Another solution is to sort the data in the template using the dictsort filter, if your data is in a list of dictionaries:

{% regroup cities|dictsort:"country" by country as country_list %}

Mengkelompokkan pada sifat lain

Any valid template lookup is a legal grouping attribute for the regroup tag, including methods, attributes, dictionary keys and list items. For example, if the "country" field is a foreign key to a class with an attribute "description," you could use:

{% regroup cities by country.description as country_list %}

Atau, jika country adalah sebuah bidang dengan choices, itu akan memiliki metode get_FOO_display() tersedia sebagai sebuah atribut, mengizinkan anda mengelompokkan pada tampilan string daripada kunci choices:

{% regroup cities by get_country_display as country_list %}

{{ country.grouper }} sekarang akan menampilan nilai bidang dari choices disetel daripada kunci.

resetcycle

Resets a previous cycle so that it restarts from its first item at its next encounter. Without arguments, {% resetcycle %} will reset the last {% cycle %} defined in the template.

Contoh penggunaan:

{% for coach in coach_list %}
    <h1>{{ coach.name }}</h1>
    {% for athlete in coach.athlete_set.all %}
        <p class="{% cycle 'odd' 'even' %}">{{ athlete.name }}</p>
    {% endfor %}
    {% resetcycle %}
{% endfor %}

Contoh ini akan mengembalikan HTML ini:

<h1>José Mourinho</h1>
<p class="odd">Thibaut Courtois</p>
<p class="even">John Terry</p>
<p class="odd">Eden Hazard</p>

<h1>Carlo Ancelotti</h1>
<p class="odd">Manuel Neuer</p>
<p class="even">Thomas Müller</p>

Notice how the first block ends with class="odd" and the new one starts with class="odd". Without the {% resetcycle %} tag, the second block would start with class="even".

Anda dapat mensetel kembali etiket siklus nama:

{% for item in list %}
    <p class="{% cycle 'odd' 'even' as stripe %} {% cycle 'major' 'minor' 'minor' 'minor' 'minor' as tick %}">
        {{ item.data }}
    </p>
    {% ifchanged item.category %}
        <h1>{{ item.category }}</h1>
        {% if not forloop.first %}{% resetcycle tick %}{% endif %}
    {% endifchanged %}
{% endfor %}

In this example, we have both the alternating odd/even rows and a "major" row every fifth row. Only the five-row cycle is reset when a category changes.

spaceless

Memindahkan ruang kosong diantara etiket HTML. Ini menyertakan karakter tab dan baris baru.

Contoh penggunaan:

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

Contoh ini akan mengembalikan HTML ini:

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

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

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

templatetag

Outputs 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.

Argumen akan memberitahu bit cetakan mana akan keluar:

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

Contoh penggunaan:

{% templatetag openblock %} url 'entry_list' {% templatetag closeblock %}

url

Returns an absolute path reference (a URL without the domain name) matching a given view and optional parameters. Any special characters in the resulting path will be encoded using iri_to_uri().

This is a way to output links without violating the DRY principle by having to hard-code URLs in your templates:

{% url 'some-url-name' v1 v2 %}

The first argument is a URL pattern name. It can be a quoted literal or any other context variable. Additional arguments are optional and should be space-separated values that will be used as arguments in the URL. The example above shows passing positional arguments. Alternatively you may use keyword syntax:

{% url 'some-url-name' arg1=v1 arg2=v2 %}

Do not mix both positional and keyword syntax in a single call. All arguments required by the URLconf should be present.

For example, suppose you have a view, app_views.client, whose URLconf takes a client ID (here, client() is a method inside the views file app_views.py). The URLconf line might look like this:

path('client/<int:id>/', app_views.client, name='app-views-client')

If this app's URLconf is included into the project's URLconf under a path such as this:

path('clients/', include('project_name.app_name.urls'))

...kemudian, dalam cetakan, anda dapat membuat sebuah tautan ke tampilan seperti ini:

{% url 'app-views-client' client.id %}

Etiket cetakan akan mengeluarkan deretan karakter /clients/client/123/.

Note that if the URL you're reversing doesn't exist, you'll get an NoReverseMatch exception raised, which will cause your site to display an error page.

If you'd like to retrieve a URL without displaying it, you can use a slightly different call:

{% url 'some-url-name' arg arg2 as the_url %}

<a href="{{ the_url }}">I'm linking to {{ the_url }}</a>

The scope of the variable created by the as var syntax is the {% block %} in which the {% url %} tag appears.

This {% url ... as var %} syntax will not cause an error if the view is missing. In practice you'll use this to link to views that are optional:

{% url 'some-url-name' as the_url %}
{% if the_url %}
  <a href="{{ the_url }}">Link to optional stuff</a>
{% endif %}

If you'd like to retrieve a namespaced URL, specify the fully qualified name:

{% url 'myapp:view-name' %}

This will follow the normal namespaced URL resolution strategy, including using any hints provided by the context as to the current application.

Peringatan

Don't forget to put quotes around the URL pattern name, otherwise the value will be interpreted as a context variable!

verbatim

Stops the template engine from rendering the contents of this block tag.

A common use is to allow a JavaScript template layer that collides with Django's syntax. For example:

{% verbatim %}
    {{if dying}}Still alive.{{/if}}
{% endverbatim %}

You can also designate a specific closing tag, allowing the use of {% endverbatim %} as part of the unrendered contents:

{% verbatim myblock %}
    Avoid template rendering via the {% verbatim %}{% endverbatim %} block.
{% endverbatim myblock %}

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.

Sebagai contoh:

<img src="bar.png" alt="Bar"
     height="10" width="{% widthratio this_value max_value max_width %}">

If this_value is 175, max_value is 200, and max_width is 100, 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).

In some cases you might want to capture the result of widthratio in a variable. It can be useful, for instance, in a blocktrans like this:

{% widthratio this_value max_value max_width as width %}
{% blocktrans %}The width is: {{ width }}{% endblocktrans %}

with

Caches a complex variable under a simpler name. This is useful when accessing an "expensive" method (e.g., one that hits the database) multiple times.

Sebagai contoh:

{% with total=business.employees.count %}
    {{ total }} employee{{ total|pluralize }}
{% endwith %}

The populated variable (in the example above, total) is only available between the {% with %} and {% endwith %} tags.

Anda dapat memberikan lebih dari satu variabel konteks:

{% with alpha=1 beta=2 %}
    ...
{% endwith %}

Catatan

The previous more verbose format is still supported: {% with business.employees.count as total %}

Petunjuk penyaring siap-pakai

add

Tambah argumen ke nilai.

Sebagai contoh:

{{ value|add:"2" }}

Jika value adalah 4, kemudian keluaran akan menjadi 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.) and fail on others. If it fails, the result will be an empty string.

Sebagai contoh, jika kami mempunyai:

{{ first|add:second }}

dan first adalah [1, 2, 3] dan second adalah [4, 5, 6], kemudian keluaran akan berupa [1, 2, 3, 4, 5, 6].

Peringatan

Strings that can be coerced to integers will be summed, not concatenated, as in the first example above.

addslashes

Tambah garis miring sebelum kutipan. Berguna untuk pelolosan string dalam CSV, sebagai contoh.

Sebagai contoh:

{{ value|addslashes }}

Jika value adalah "I'm using Django", keluaran akan berupa "I\'m using Django".

capfirst

Capitalizes the first character of the value. If the first character is not a letter, this filter has no effect.

Sebagai contoh:

{{ value|capfirst }}

Jika value adalah "django", keluaran akan menjadi "Django".

center

Tengahkan nilai di bidang dari lebar yang diberikan.

Sebagai contoh:

"{{ value|center:"15" }}"

Jika value adalah "Django", keluaran akan menjadi " Django ".

cut

Memindahkan semua nilai dari arg dari string yang diberikan.

Sebagai contoh:

{{ value|cut:" " }}

Jika value adalah "String with spaces", keluaran akan berupa "Stringwithspaces".

date

Bentuk tanggal menurut pada bentuk yang diberikan.

Menggunakan bentuk yang mirip seperti fungsi date() PHP (https://php.net/date) dengan beberapa perbedaan.

Catatan

These format characters are not used in Django outside of templates. They were designed to be compatible with PHP to ease transitioning for designers.

String bentuk tersedia:

Bentuk karakter Deskripsi Contoh keluaran
Hari    
d Hari dari bulan, 2 angka dengan dimulai nol. '01' sampai '31'
j Hari dari bulan tanpa dimulai nol. '1' sampai '31'
D Hari dari minggu, tekstual, 3 huruf. 'Fri'
l Hari dari minggu, tekstual, panjang. 'Jumat'
S English ordinal suffix for day of the month, 2 characters. 'st', 'nd', 'rd' or 'th'
w Hari dari minggu, angka tanpa dimulai nol. '0' (Minggu) sampai '6' (Sabtu)
z Hari dari tahun. 1 to 366
Minggu    
W Angka minggu ISO-8601 dari tahun, dengan minggu dimulai pada Senin. 1, 53
Bulan    
m Bulan, 2 angka tanpa dimulai nol. '01' sampai '12'
n Bulan tanpa dimulai dengan nol. '1' sampai '12'
M Bulan, tektual, 3 huruf. 'Jan'
b Bulan, tekstual, 3 huruf, huruf kecil. 'jan'
E Month, locale specific alternative representation usually used for long date representation. 'listopada' (untuk lokal Polandia, sebagai lawan terhadap 'Listopad')
F Bulan, tektual, panjang. 'Januari'
N Month abbreviation in Associated Press style. Proprietary extension. 'Jan.', 'Feb.', 'Maret', 'Mei'
t Jumlah hari dalam bulan yang diberikan. 28 sampai 31
Tahun    
y Tahun, 2 angka. '99'
Y Tahun, 4 angka. '1999'
L Boolean untuk apakah itu adalah tahun kabisat. True atau False
o ISO-8601 week-numbering year, corresponding to the ISO-8601 week number (W) which uses leap weeks. See Y for the more common year format. '1999'
Waktu    
g Jam, bentuk 12-jam tanpa diawali nol. '1' sampai '12'
G Jam, bentuk 24-jam tanpa diawali nol. '0' sampai '23'
h Jam, bentuk 12-jam. '01' sampai '12'
H Jam, bentuk 24-jam. '00' sampai '23'
i Menit. '00' sampai '59'
s Dua, 2 angka dengan awal nol. '00' sampai '59'
u Mikrodetik 000000 sampai 999999
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' atau 'PM'. 'AM'
f Time, in 12-hour hours and minutes, with minutes left off if they're zero. Proprietary extension. '1', '1:30'
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.'
Zona waktu    
e Timezone name. Could be in any format, or might return an empty string, depending on the datetime. '', 'GMT', '-500', 'US/Eastern', etc.
I Daylight Savings Time, apakah itu berpengaruh atau tidak. '1' atau '0'
O Perbedaan pada waktu Greenwich dalam jam. '+0200'
T Zona waktu dari mesin ini. 'EST', 'MDT'
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 sampai 43200
Tanggal/Waktu    
c ISO 8601 format. (Note: unlike others formatters, such as "Z", "O" or "r", the "c" formatter will not add timezone offset if value is a naive datetime (see datetime.tzinfo). 2008-01-02T10:30:00.000123+02:00, atau 2008-01-02T10:30:00.000123 jika datetime tidak dibuat-buat
r RFC 5322 formatted date. 'Kam, 21 Des 2000 16:01:07 +0200'
U Dua sejak Unix Epoch (January 1 1970 00:00:00 UTC).  

Sebagai contoh:

{{ value|date:"D d M Y" }}

If value is a datetime object (e.g., the result of datetime.datetime.now()), the output will be the string 'Wed 09 Jan 2008'.

The format passed can be one of the predefined ones DATE_FORMAT, DATETIME_FORMAT, SHORT_DATE_FORMAT or SHORT_DATETIME_FORMAT, or a custom format that uses the format specifiers shown in the table above. Note that predefined formats may vary depending on the current locale.

Menganggap itu USE_L10N adalah True dan LANGUAGE_CODE, sebagai contoh, "es", kemudian untuk:

{{ value|date:"SHORT_DATE_FORMAT" }}

the output would be the string "09/01/2008" (the "SHORT_DATE_FORMAT" format specifier for the es locale as shipped with Django is "d/m/Y").

When used without a format string, the DATE_FORMAT format specifier is used. Assuming the same settings as the previous example:

{{ value|date }}

outputs 9 de Enero de 2008 (the DATE_FORMAT format specifier for the es locale is r'j \d\e F \d\e Y'.

You can combine date with the time filter to render a full representation of a datetime value. E.g.:

{{ value|date:"D d M Y" }} {{ value|time:"H:i" }}

default

Jika nilai dinilai ke False, gunakan awal yang diberikan. Sebaliknya, gunakan nilai.

Sebagai contoh:

{{ value|default:"nothing" }}

Jika value adalah "" (string kosong), keluaran akan berupa nothing.

default_if_none

Jika (dan hanya jika) nilai adalah None, gunakan awal yang diberikan. Sebaliknya, gunakan nilai.

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.

Sebagai contoh:

{{ value|default_if_none:"nothing" }}

Jika value adalah None, keluaran akan berupa nothing.

dictsort

Takes a list of dictionaries and returns that list sorted by the key given in the argument.

Sebagai contoh:

{{ value|dictsort:"name" }}

Jika value adalah:

[
    {'name': 'zed', 'age': 19},
    {'name': 'amy', 'age': 22},
    {'name': 'joe', 'age': 31},
]

kemudian keluarannya akan menjadi:

[
    {'name': 'amy', 'age': 22},
    {'name': 'joe', 'age': 31},
    {'name': 'zed', 'age': 19},
]

Anda dapat juga melakukan hal-hal lebih rumit seperti:

{% for book in books|dictsort:"author.age" %}
    * {{ book.title }} ({{ book.author.name }})
{% endfor %}

Jika books adalah:

[
    {'title': '1984', 'author': {'name': 'George', 'age': 45}},
    {'title': 'Timequake', 'author': {'name': 'Kurt', 'age': 75}},
    {'title': 'Alice', 'author': {'name': 'Lewis', 'age': 33}},
]

kemudian keluarannya akan menjadi:

* Alice (Lewis)
* 1984 (George)
* Timequake (Kurt)

dictsort can also order a list of lists (or any other object implementing __getitem__()) by elements at specified index. For example:

{{ value|dictsort:0 }}

Jika value adalah:

[
    ('a', '42'),
    ('c', 'string'),
    ('b', 'foo'),
]

kemudian keluarannya akan menjadi:

[
    ('a', '42'),
    ('b', 'foo'),
    ('c', 'string'),
]

You must pass the index as an integer rather than a string. The following produce empty output:

{{ values|dictsort:"0" }}

dictsortreversed

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.

divisibleby

Mengembalikan True jika nilai terbagi oleh argumen.

Sebagai contoh:

{{ value|divisibleby:"3" }}

Jika value adalah 21, keluaran akan menjadi True.

escape

Meloloskan HTML string. Khususnya, itu membuat pergantian ini:

  • < dirubah ke &lt;
  • > dirubah ke &gt;
  • ' (kutip tunggal) dirubah ke &#39;
  • " (kutip ganda) dirubah ke &quot;
  • & dirubah ke &amp;

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. If you want multiple escaping passes to be applied, use the force_escape filter.

Sebagai contoh, anda dapat memberlakukan escape pada bidang ketika autoescape mati:

{% autoescape off %}
    {{ title|escape }}
{% endautoescape %}

escapejs

Escapes characters for use in JavaScript strings. This does not make the string safe for use in HTML or JavaScript template literals, but does protect you from syntax errors when using templates to generate JavaScript/JSON.

Sebagai contoh:

{{ value|escapejs }}

Jika value adalah "testing\r\njavascript \'string" <b>escaping</b>", keluaran akan berupa "testing\\u000D\\u000Ajavascript \\u0027string\\u0022 \\u003Cb\\u003Eescaping\\u003C/b\\u003E".

filesizeformat

membentuk nilai seperti ukuran berkas 'dapat-dibaca-manusia' (yaitu '13 KB', '4.1 MB', '102 bytes', dll.).

Sebagai contoh:

{{ value|filesizeformat }}

Jika value adalah 123456789, keluaran akan berupa 117.7 MB.

Ukuran berkas dan satuan SI

Strictly speaking, filesizeformat does not conform to the International System of Units which recommends using KiB, MiB, GiB, etc. when byte sizes are calculated in powers of 1024 (which is the case here). Instead, Django uses traditional unit names (KB, MB, GB, etc.) corresponding to names that are more commonly used.

first

Mengembalikan barang pertama dalam sebuah list.

Sebagai contoh:

{{ value|first }}

Jika value adalah list ['a', 'b', 'c'], keluaran akan berupa 'a'.

floatformat

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. For example:

value Cetakan Keluaran
34.23234 {{ value|floatformat }} 34.2
34.00000 {{ value|floatformat }} 34
34.26000 {{ value|floatformat }} 34.3

Jika digunakan dengan argumen integer numerik, floatformat membulatkan ke sebanyak tempat desimal. Sebagai contoh:

value Cetakan Keluaran
34.23234 {{ value|floatformat:3 }} 34.232
34.00000 {{ value|floatformat:3 }} 34.000
34.26000 {{ value|floatformat:3 }} 34.260

Particularly useful is passing 0 (zero) as the argument which will round the float to the nearest integer.

value Cetakan Keluaran
34.23234 {{ value|floatformat:"0" }} 34
34.00000 {{ value|floatformat:"0" }} 34
39.56000 {{ value|floatformat:"0" }} 40

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. For example:

value Cetakan Keluaran
34.23234 {{ value|floatformat:"-3" }} 34.232
34.00000 {{ value|floatformat:"-3" }} 34
34.26000 {{ value|floatformat:"-3" }} 34.260

Using floatformat with no argument is equivalent to using floatformat with an argument of -1.

force_escape

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.

Sebagai contoh, jika anda ingin menangkap <p> unsur HTML dibuat oleh penyaring linebreaks:

{% autoescape off %}
    {{ body|linebreaks|force_escape }}
{% endautoescape %}

get_digit

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.

Sebagai contoh:

{{ value|get_digit:"2" }}

Jika value adalah 123456789, keluaran akan menjadi 8.

iriencode

Converts an IRI (Internationalized Resource Identifier) to a string that is suitable for including in a URL. This is necessary if you're trying to use strings containing non-ASCII characters in a URL.

Itu adalah aman menggunakan penyaring ini pada string yang sudah hilang melalui penyaring urlencode.

Sebagai contoh:

{{ value|iriencode }}

Jika value adalah "?test=1&me=2", keluaran akan menjadi "?test=1&amp;me=2".

join

Menggabungkan list dengan string, seperti str.join(list) Python

Sebagai contoh:

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

Jika value adalah daftar ['a', 'b', 'c'], keluaran akan menjadi deretan karakter "a // b // c".

json_script

New in Django 2.1.

Dengan aman mengeluarkan sebuah obyek Python sebagai JSON, dibungkus dalam sebuah etiket <script>, siap digunakan dengan JavaScript.

Argumen: "id" HTML dari etiket <script>.

Sebagai contoh:

{{ value|json_script:"hello-data" }}

Jika value adalah dictionary {'hello': 'world'}, keluaran akan berupa:

<script id="hello-data" type="application/json">{"hello": "world"}</script>

Data hasil dapat diakses dalam JavaScript seperti ini:

var value = JSON.parse(document.getElementById('hello-data').textContent);

Serangan XSS dikurangi dengan meloloskan karakter "<", ">" dan "&". Sebagai contoh jika value adalah {'hello': 'world</script>&amp;'}, keluaran adalah:

<script id="hello-data" type="application/json">{"hello": "world\\u003C/script\\u003E\\u0026amp;"}</script>

This is compatible with a strict Content Security Policy that prohibits in-page script execution. It also maintains a clean separation between passive data and executable code.

last

Mengembalikan barang terakhir di daftar.

Sebagai contoh:

{{ value|last }}

Jika value adalah daftar ['a', 'b', 'c', 'd'], keluaran akan menjadi deretan karakter "d".

length

Mengembalikan panjang nilai. Ini bekerja pada kedua deretan karakter dan daftar.

Sebagai contoh:

{{ value|length }}

Jika value adalah ['a', 'b', 'c', 'd'] atau "abcd", keluaran akan menjadi 4.

Penyaring mengembalikan 0 untuk variabel tidak ditentukan.

length_is

Mengembalikan True jika panjang nilai adalah argumen, atau False sebaliknya.

Sebagai contoh:

{{ value|length_is:"4" }}

Jika value adalah ['a', 'b', 'c', 'd'] atau "abcd", keluaran akan menjadi True.

linebreaks

Replaces line breaks in plain text with appropriate HTML; a single newline becomes an HTML line break (<br>) and a new line followed by a blank line becomes a paragraph break (</p>).

Sebagai contoh:

{{ value|linebreaks }}

Jika value adalah Joel\nis a slug, keluaran akan berupa <p>Joel<br>is a slug</p>.

linebreaksbr

Merubah semua baris baru dalam potongan teks polos menjadi jeda baris HTML (<br>).

Sebagai contoh:

{{ value|linebreaksbr }}

Jika value adalah Joel\nis a slug, keluaran akan berupa Joel<br>is a slug.

linenumbers

Menampilkan teks dengan baris angka.

Sebagai contoh:

{{ value|linenumbers }}

Jika value adalah:

one
two
three

keluaran akan menjadi:

1. one
2. two
3. three

ljust

Rata-kiri nilai dalam sebuah bidang dari lebar yang diberikan.

Argumen: ukuran bidang

Sebagai contoh:

"{{ value|ljust:"10" }}"

Jika value adalah Django, keluaran akan berupa "Django    ".

lower

Merubah string menjadi huruf kecil semua.

Sebagai contoh:

{{ value|lower }}

Jika value adalah Totally LOVING this Album!, keluaran akan berupa totally loving this album!.

make_list

Returns the value turned into a list. For a string, it's a list of characters. For an integer, the argument is cast to a string before creating a list.

Sebagai contoh:

{{ value|make_list }}

Jika value adalah string "Joel", keluara akan berupa list ['J', 'o', 'e', 'l']. Jika value adalah 123, keluaran akan berupa list ['1', '2', '3'].

phone2numeric

Merubah nomor telepon (kemunginan mengandung huruf) ke setara numeriknya.

Masukan tidak harus berupa nomor telepon sah. Ini akan membuat bahagia merubah string apapun.

Sebagai contoh:

{{ value|phone2numeric }}

Jika value adalah 800-COLLECT, keluaran akan berupa 800-2655328.

pluralize

Returns a plural suffix if the value is not 1, '1', or an object of length 1. By default, this suffix is 's'.

Contoh:

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

Jika num_messages adalah 1, keluaran kan berupa You have 1 message. Jika num_messages adalah 2 keluaran akan berupa You have 2 messages.

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

Contoh:

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

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

Contoh:

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

Catatan

Gunakan blocktrans untuk menjamakkan string terjemahan.

pprint

Sebuah pembungkus disekitar pprint.pprint() -- untuk mencari kesalahan, sungguh.

random

Mengembalikan barang acak dari list yang diberikan.

Sebagai contoh:

{{ value|random }}

Jika value adalah list ['a', 'b', 'c', 'd'], keluaran akan berupa "b".

rjust

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

Argumen: ukuran bidang

Sebagai contoh:

"{{ value|rjust:"10" }}"

Jika value adalah Django, keluaran akan menjadi " Django".

safe

Marks a string as not requiring further HTML escaping prior to output. When autoescaping is off, this filter has no effect.

Catatan

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:

{{ var|safe|escape }}

safeseq

Applies the safe filter to each element of a sequence. Useful in conjunction with other filters that operate on sequences, such as join. For example:

{{ some_list|safeseq|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.

slice

Mengembalikan potongan dari list.

Uses the same syntax as Python's list slicing. See https://www.diveinto.org/python3/native-datatypes.html#slicinglists for an introduction.

Contoh:

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

Jika some_list is ['a', 'b', 'c'], keluaran akn berupa ['a', 'b'].

slugify

Merubah ke ASCII. Merubah ruang menjadi tanda garis. Memindahkan karakter yang tidak alphanumerik, garis bawah, atau tanda garis. Merubah ke huruf kecil. Juga melucuti terkemuka dan buntutan ruang kosong.

Sebagai contoh:

{{ value|slugify }}

Jika value adalah "Joel is a slug", keluaran akan berupa "joel-is-a-slug".

stringformat

Formats the variable according to the argument, a string formatting specifier. This specifier uses the printf-style String Formatting syntax, with the exception that the leading "%" is dropped.

Sebagai contoh:

{{ value|stringformat:"E" }}

Jika value adalah 10, keluaran kana berupa 1.000000E+01.

striptags

Membuat semua kemungkinan usaha untuk menghapus semua etiket [X]HTML.

Sebagai contoh:

{{ value|striptags }}

Jika value adalah "<b>Joel</b> <button>is</button> a <span>slug</span>", keluaran akan berupa "Joel is a slug".

Tidak ada jaminan keamanan

Note that striptags doesn't give any guarantee about its output being HTML safe, particularly with non valid HTML input. So NEVER apply the safe filter to a striptags output. If you are looking for something more robust, you can use the bleach Python library, notably its clean method.

time

Bentuk waktu menurut pada bentuk yang diberikan.

Given format can be the predefined one TIME_FORMAT, or a custom format, same as the date filter. Note that the predefined format is locale-dependent.

Sebagai contoh:

{{ value|time:"H:i" }}

Jika value setara pada datetime.datetime.now(), keluaran akan berupa string "01:23".

Contoh lain:

Anggap bahwa USE_L10N adalah True dan LANGUAGE_CODE adalah, sebagai contoh, "de", kemudian untuk:

{{ value|time:"TIME_FORMAT" }}

the output will be the string "01:23" (The "TIME_FORMAT" format specifier for the de locale as shipped with Django is "H:i").

The time filter will only accept parameters in the format string that relate to the time of day, not the date (for obvious reasons). If you need to format a date value, use the date filter instead (or along time if you need to render a full datetime value).

There is one exception the above rule: When passed a datetime value with attached timezone information (a time-zone-aware datetime instance) the time filter will accept the timezone-related format specifiers 'e', 'O' , 'T' and 'Z'.

Ketika digunakan tanpa bentuk string, penentu bentuk TIME_FORMAT digunakan:

{{ value|time }}

adalah sama seperti:

{{ value|time:"TIME_FORMAT" }}

timesince

Bentuk tanggal seperti waktu sejak tanggal itu (misalnya, "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 the following would return "8 hours":

{{ blog_date|timesince:comment_date }}

Comparing offset-naive and offset-aware datetimes will return an empty string.

Minutes is the smallest unit used, and "0 minutes" will be returned for any date that is in the future relative to the comparison point.

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 "4 weeks".

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 the following will return "1 week":

{{ conference_date|timeuntil:from_date }}

Comparing offset-naive and offset-aware datetimes will return an empty string.

Minutes is the smallest unit used, and "0 minutes" will be returned for any date that is in the past relative to the comparison point.

title

Converts a string into titlecase by making words start with an uppercase character and the remaining characters lowercase. This tag makes no effort to keep "trivial words" in lowercase.

Sebagai contoh:

{{ value|title }}

Jika value adalah "my FIRST post",keluaran akan berupa "My First Post".

truncatechars

Truncates a string if it is longer than the specified number of characters. Truncated strings will end with a translatable ellipsis character ("…").

Argumen: Jumah karakter dipotong

Sebagai contoh:

{{ value|truncatechars:7 }}

If value is "Joel is a slug", the output will be "Joel i…".

truncatechars_html

Similar to truncatechars, except that it is aware of HTML tags. Any tags that are opened in the string and not closed before the truncation point are closed immediately after the truncation.

Sebagai contoh:

{{ value|truncatechars_html:7 }}

If value is "<p>Joel is a slug</p>", the output will be "<p>Joel i…</p>".

Baris baru dalam isi HTML akan dipertahankan

truncatewords

Memotong sebuah string setelah sejumlah angka dari kata.

Argumen: Jumlah kata untuk dipotong setelahnya

Sebagai contoh:

{{ value|truncatewords:2 }}

Jika value adalah "Joel is a slug", keluaran akan berupa "Joel is …".

Baris baru dalam string akan dipindahkan.

truncatewords_html

Similar to truncatewords, except that it is aware of HTML tags. Any tags that are opened in the string and not closed before the truncation point, are closed immediately after the truncation.

This is less efficient than truncatewords, so should only be used when it is being passed HTML text.

Sebagai contoh:

{{ value|truncatewords_html:2 }}

Jika value adalah "<p>Joel is a slug</p>", keluaran akan berupa "<p>Joel is …</p>".

Baris baru dalam isi HTML akan dipertahankan

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

Merubah string kedalam semua huruf besar.

Sebagai contoh:

{{ value|upper }}

Jika value adalah "Joel is a slug", keluaran akan berupa "JOEL IS A SLUG".

urlencode

Meloloskan sebuah nilai untuk digunakan dalam sebuah URL.

Sebagai contoh:

{{ value|urlencode }}

Jika value adalah "https://www.example.org/foo?a=b&c=d", keluaran akan berupa "https%3A//www.example.org/foo%3Fa%3Db%26c%3Dd".

Sebuah argumen pilihan mengandung karakter yang harus tidak diloloskan dapat disediakan.

If not provided, the '/' character is assumed safe. An empty string can be provided when all characters should be escaped. For example:

{{ value|urlencode:"" }}

If value is "https://www.example.org/", the output will be "https%3A%2F%2Fwww.example.org%2F".

urlize

Merubah URL dan alamat surel dalam teks menjadi tautan dapat di klik.

This template tag works on links prefixed with http://, https://, or www.. For example, https://goo.gl/aia1t will get converted but goo.gl/aia1t won't.

It also supports domain-only links ending in one of the original top level domains (.com, .edu, .gov, .int, .mil, .net, and .org). For example, djangoproject.com gets converted.

Links can have trailing punctuation (periods, commas, close-parens) and leading punctuation (opening parens), and urlize will still do the right thing.

Tautan yang dibangkitkan oleh urlize mempunyai sebuah atribut rel="nofollow" ditambahkan ke mereka.

Sebagai contoh:

{{ value|urlize }}

If value is "Check out www.djangoproject.com", the output will be "Check out <a href="http://www.djangoproject.com" rel="nofollow">www.djangoproject.com</a>".

In addition to web links, urlize also converts email addresses into mailto: links. If value is "Send questions to foo@example.com", the output will be "Send questions to <a href="mailto:foo@example.com">foo@example.com</a>".

The urlize filter also takes an optional parameter autoescape. If autoescape is True, the link text and URLs will be escaped using Django's built-in escape filter. The default value for autoescape is True.

Catatan

If urlize is applied to text that already contains HTML markup, or to email addresses that contain single quotes ('), things won't work as expected. Apply this filter only to plain text.

urlizetrunc

Converts URLs and email addresses into clickable links just like urlize, but truncates URLs longer than the given character limit.

Argument: Number of characters that link text should be truncated to, including the ellipsis that's added if truncation is necessary.

Sebagai contoh:

{{ value|urlizetrunc:15 }}

Jika value adalaj "Check out www.djangoproject.com", keluaran akan berupa 'Check out <a href="http://www.djangoproject.com" rel="nofollow">www.djangoproj…</a>'.

As with urlize, this filter should only be applied to plain text.

wordcount

Mengembalikan sejumlah kata.

Sebagai contoh:

{{ value|wordcount }}

Jika value adalah "Joel is a slug", keluaran akan menjadi 4.

wordwrap

Membungkus kata pada panjang baris ditentukan.

Argumen: jumlah dari karakter dimana membungkus teks

Sebagai contoh:

{{ value|wordwrap:5 }}

Jika value is Joel is a slug, keluaran akan menjadi:

Joel
is a
slug

yesno

Maps values for True, False, and (optionally) None, to the strings "yes", "no", "maybe", or a custom mapping passed as a comma-separated list, and returns one of those strings according to the value:

Sebagai contoh:

{{ value|yesno:"yeah,no,maybe" }}
Nilai Argument Keluaran
True   yes
True "yeah,no,maybe" yeah
False "yeah,no,maybe" no
None "yeah,no,maybe" maybe
None "yeah,no" no (merubah None menjadi False jika tidak ada pemetaan untuk None diberikan)

Internationalization tags and filters

Django provides template tags and filters to control each aspect of internationalization in templates. They allow for granular control of translations, formatting, and time zone conversions.

i18n

This library allows specifying translatable text in templates. To enable it, set USE_I18N to True, then load it with {% load i18n %}.

Lihat Internasionalisasi: dalam kode cetakan.

l10n

This library provides control over the localization of values in templates. You only need to load the library using {% load l10n %}, but you'll often set USE_L10N to True so that localization is active by default.

Lihat Mengendalikan lokalisasi dalam cetakan-cetakan.

tz

This library provides control over time zone conversions in templates. Like l10n, you only need to load the library using {% load tz %}, but you'll usually also set USE_TZ to True so that conversion to local time happens by default.

Lihat Time zone aware output in templates.

Other tags and filters 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 django.contrib.humanize.

static

static

To link to static files that are saved in STATIC_ROOT Django ships with a static template tag. If the django.contrib.staticfiles app is installed, the tag will serve files using url() method of the storage specified by STATICFILES_STORAGE. For example:

{% load static %}
<img src="{% static "images/hi.jpg" %}" alt="Hi!">

It is also able to consume standard context variables, e.g. assuming a user_stylesheet variable is passed to the template:

{% load static %}
<link rel="stylesheet" href="{% static user_stylesheet %}" type="text/css" media="screen">

If you'd like to retrieve a static URL without displaying it, you can use a slightly different call:

{% load static %}
{% static "images/hi.jpg" as myphoto %}
<img src="{{ myphoto }}">

Menggunakan cetakan Jinja2?

See Jinja2 for information on using the static tag with Jinja2.

get_static_prefix

You should prefer the static template tag, but if you need more control over exactly where and how STATIC_URL is injected into the template, you can use the get_static_prefix template tag:

{% load static %}
<img src="{% get_static_prefix %}images/hi.jpg" alt="Hi!">

There's also a second form you can use to avoid extra processing if you need the value multiple times:

{% load static %}
{% get_static_prefix as STATIC_PREFIX %}

<img src="{{ STATIC_PREFIX }}images/hi.jpg" alt="Hi!">
<img src="{{ STATIC_PREFIX }}images/hi2.jpg" alt="Hello!">

get_media_prefix

Similar to the get_static_prefix, get_media_prefix populates a template variable with the media prefix MEDIA_URL, e.g.:

{% load static %}
<body data-media-url="{% get_media_prefix %}">

By storing the value in a data attribute, we ensure it's escaped appropriately if we want to use it in a JavaScript context.

Back to Top