組み込みタグとフィルタLink to this heading

このドキュメントでは、 Django の組み込みテンプレートタグとフィルタについて述べます。 また automatic documentation を使えばインストールされている組み込みタグとカスタムタグのドキュメントを読めるのでお勧めです。

組み込みタグリファレンスLink to this heading

autoescapeLink to this heading

自動エスケープ機能を制御します。このタグは引数に on または off を取り、ブロック内の自動エスケープの有効・無効を決定します。ブロックの最後は endautoescape タグで閉じるようにします。

Sample usage:

Django template
{% autoescape on %}
    {{ body }}
{% endautoescape %}

When auto-escaping is in effect, all content derived from variables has HTML escaping applied before placing the result into the output (but after any filters are applied). This is equivalent to manually applying the escape filter to each variable.

The only exceptions are variables already marked as "safe" from escaping. Variables could be marked as "safe" by the code which populated the variable, by applying the safe or escape filters, or because it's the result of a previous filter that marked the string as "safe".

Within the scope of disabled auto-escaping, chaining filters, including escape, may cause unexpected (but documented) results such as the following:

Django template
{% autoescape off %}
    {{ my_list|join:", "|escape }}
{% endautoescape %}

The above code will output the joined elements of my_list unescaped. This is because the filter chaining sequence executes first join on my_list (without applying escaping to each item since autoescape is off), marking the result as safe. Subsequently, this safe result will be fed to escape filter, which does not apply a second round of escaping.

blockLink to this heading

子テンプレートによってオーバーライドされる部分を定義します。詳しくは Template inheritance を参照してください。

commentLink to this heading

{% comment %}{% endcomment %} で囲まれた部分はすべて無視されます。最初のタグには追加の説明文を含めるすることができます。例えばコードの一部をコメント化した際、その部分を無効にした理由を記述したいときなどに便利です。

Sample usage:

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

comment タグを入れ子にすることはできません。

csrf_tokenLink to this heading

このタグは CSRF の防止のために使用します。詳細は Cross Site Request Forgeries を参照してください。.

cycleLink to this heading

タグを実行するごとに、引数の文字列や変数から、順に一つずつ値を出力します。最初の処理では 1 番目の値が、その次に 2 番目の値、以下、4 個まで同様に処理されます。サイクルのすべての値を出力すると、再び 1 番目に戻って出力します。

This tag is particularly useful in a loop:

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

この例では、繰り返しの最初の実行では row1 クラスを参照する HTML が生成されます。 2 回目には row2、 3 回目は再び row1 というように、ループを繰り返すたびに交互に処理されます。

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

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

Variables included in the cycle will be escaped. You can disable auto-escaping with:

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

You can mix variables and strings:

Django template
{% 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, give the {% cycle %} tag a name, using "as", like this:

Django template
{% 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:

Django 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>

would output:

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

cycle タグ内では、空白で区切ることでいくつでも値を使うことができます。一重引用符 ( ' ) または二重引用符 ( " ) で囲まれた値は文字列リテラルとして扱われ、引用符のない値はテンプレート変数として扱われます。

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:

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

これは <tr> エレメントのリストを出力し、 class には row1row2 が交互に設定されます。サブテンプレートではそのコンテキスト内で rowcolors にアクセスし、値はそれを取り囲む <tr> のクラスに一致します。ここでもし silent キーワードが無かったら、 row1row2<tr> エレメントの外側で通常のテキストとして発行されます。

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:

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

You can use the resetcycle tag to make a {% cycle %} tag restart from its first value when it's next encountered.

debugLink to this heading

Outputs a whole load of debugging information, including the current context and imported modules. {% debug %} outputs nothing when the DEBUG setting is False.

extendsLink to this heading

このテンプレートが親テンプレートからの拡張であることを指示します。

このタグには 2 種類の使い方があります:

  • {% extends "base.html" %} (引用符つき) の場合、リテラル値 "base.html" を親テンプレートの名前として使います。

  • {% extends variable %} とした場合、変数 variable の値を親テンプレートの名前として使います。変数の値が文字列の場合、 Django はその文字列を親テンプレートの名前として使います。値が Template オブジェクトの場合、Django はそのオブジェクトを親テンプレートにします。

詳しくは テンプレートの継承 を参照してください。

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:

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

In template.html, the following paths would be valid:

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

filterLink to this heading

タグブロック内のコンテンツを、1 つまたは複数のフィルタに通します。複数のフィルタを使うときはパイプ( " | " )を使って連結します。フィルタには変数のように引数を与えることができます。

filter タグと endfilter タグに囲まれたテキストは、すべて ブロックに含まれることに注意しましょう。

Sample usage:

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

firstofLink to this heading

Outputs the first argument variable that is not "false" (i.e. exists, is not empty, is not a false boolean value, and is not a zero numeric value). Outputs nothing if all the passed variables are "false".

Sample usage:

Django template
{% firstof var1 var2 var3 %}

This is equivalent to:

Django template
{% 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:

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

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

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

Or if only some variables should be escaped, you can use:

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

{% firstof var1 var2 var3 as value %} と記述することで、出力を 1 つの変数内に格納することができます。

forLink to this heading

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:

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

{% 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:

Django template
{% 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:

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

ドット演算子を使う場合、メソッドよりも辞書キーへの参照が優先することに注意してください。したがって、もしも data 辞書が 'items' という名前のキーを持っていたなら、 data.itemsdata.items() ではなく data['items'] の値を出力します。テンプレート内で辞書のメソッドを使いたい場合、そのような名前のキー (itemsvalueskeys など) を辞書に追加しないでください。ドット演算子による参照の優先順位についての詳細は documentation of template variables を参照してください。

for ループには、ループ内で使える多くの変数が設定されています:

変数

説明

forloop.counter

現在のループカウンタ番号 ( 1 から順にカウント )

forloop.counter0

現在のループカウンタ番号 ( 0 から順にカウント )

forloop.revcounter

現在のループカウンタ値 ( 1 から順に、末尾からカウント)

forloop.revcounter0

現在のループカウンタ値 ( 0 から順に、末尾からカウント)

forloop.first

最初のループであれば True

forloop.last

最後のループであれば True

forloop.parentloop

入れ子のループであるとき、現在のループを囲んでいる 1 つ上のループを表します。

for ... emptyLink to this heading

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

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

The above is equivalent to -- but shorter, cleaner, and possibly faster than -- the following:

Django template
<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>

ifLink to this heading

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:

Django template
{% 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 %}

上の例では、 athlete_list が空でなければ、アスリートの人数を {{ athlete_list|length }} 変数で表示します。

例にもあるように if タグはオプションで 1 個以上の {% elif %} 節、および 1 個の {% else %} 節をつけることができます。 {% else %} はそれまでの評価結果がすべて True でなかった場合に表示されるコンテンツを定義します。

論理演算子Link to this heading

if tags may use and, or or not to test a number of variables or to negate a given variable:

Django template
{% 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.:

Django template
{% if athlete_list and coach_list or cheerleader_list %}

これは以下のように解釈されます:

Python console
if (athlete_list and coach_list) or cheerleader_list

実際には if タグの中で丸括弧を使うことはできません。優先順位を示す必要がある場合には、if タグを入れ子にして表してください。

if タグは演算子 ==, !=, <, >, <=, >=, in, not in, is, and is not が使え、以下のように機能します:

== 演算子Link to this heading

Equality. Example:

Django template
{% if somevar == "x" %}
  This appears if variable somevar equals the string "x"
{% endif %}
!= 演算子Link to this heading

Inequality. Example:

Django template
{% if somevar != "x" %}
  This appears if variable somevar does not equal the string "x",
  or if somevar is not found in the context
{% endif %}
< 演算子Link to this heading

Less than. Example:

Django template
{% if somevar < 100 %}
  This appears if variable somevar is less than 100.
{% endif %}
> 演算子Link to this heading

Greater than. Example:

Django template
{% if somevar > 0 %}
  This appears if variable somevar is greater than 0.
{% endif %}
<= 演算子Link to this heading

Less than or equal to. Example:

Django template
{% if somevar <= 100 %}
  This appears if variable somevar is less than 100 or equal to 100.
{% endif %}
>= 演算子Link to this heading

Greater than or equal to. Example:

Django template
{% if somevar >= 1 %}
  This appears if variable somevar is greater than 1 or equal to 1.
{% endif %}
in 演算子Link to this heading

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:

Django template
{% 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 %}
not in 演算子Link to this heading

コンテナに含まれていない場合。これは in 演算子の逆です。

is 演算子Link to this heading

Object identity. Tests if two values are the same object. Example:

Django template
{% 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 %}
is not operatorLink to this heading

Negated object identity. Tests if two values are not the same object. This is the negation of the is operator. Example:

Django template
{% 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 %}

フィルターLink to this heading

You can also use filters in the if expression. For example:

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

複雑な表現Link to this heading

ここまでのすべてを組み合わせて複雑な式を作ることができます。このような式では、式を評価するときに演算子がどのようにグループ化されるか、すなわち優先順位の規則を理解することが重要です。演算子の優先順位は次のようになっています:

  • or

  • and

  • not

  • in

  • ==, !=, <, >, <=, >=

(This follows Python exactly). So, for example, the following complex if tag:

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

...次のように解釈されます:

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

もしこれと違った優先順位が必要ならば、if タグを入れ子にして使う必要があります。優先順位の規則がはっきりしない場合には、こうした方がより明確な表現になることもあるでしょう。

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

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

you should use:

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

ifchangedLink to this heading

値が前回のループ実行時から変わっているかどうかを調べます。

{% ifchanged %} ブロックタグはループの内部で使います。このタグには 2 通りの使い方があります。

  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:

    Django template
    <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:

    Django template
    {% 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:

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

includeLink to this heading

テンプレートをロードし、現在のコンテキストを使って出力します。これはテンプレート内に他のテンプレートを取り込む( “include” )方法の一つです。

テンプレート名はハードコードされた (引用符で囲った) 文字列でもよく、引用符は一重引用符 ('...')でも二重引用符("...")でもかまいません。

This example includes the contents of the template "foo/bar.html":

Django template
{% 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.

This example includes the contents of the template whose name is contained in the variable template_name:

Django template
{% include template_name %}

変数は、コンテキストを受け取る render() メソッドを持っていればオブジェクトでも構いません。これによって、コンテキスト内のコンパイル済みの Template を参照することができます。

Additionally, the variable may be an iterable of template names, in which case the first that can be loaded will be used, as per select_template().

include されたテンプレートは、include した側のコンテキストにおいて解釈されます。以下の例は "Hello, John!" を出力します:

  • コンテキスト: 変数 person"John" を、変数 greeting"Hello" をセット。

  • Template:

    Django template
    {% include "name_snippet.html" %}
    
  • The name_snippet.html template:

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

You can pass additional context to the template using keyword arguments:

Django template
{% 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:

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

loadLink to this heading

カスタムのテンプレートタグセットを読み込みます。

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

Django template
{% 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:

Django template
{% load foo bar from somelibrary %}

詳しくは Custom tag and filter libraries を参照してください。

loremLink to this heading

ランダムな"lorem ipsum" のラテン語テキストを表示させます。テンプレート内でサンプルデータを用意するのに便利です。

Usage:

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

{% lorem %} タグは 0 から 3 個の引数をとります:

Argument

説明

count

生成する単語または段落の数を指定する、数値または変数 (デフォルトは 1 ) 。

method

w のとき単語を、p のとき HTML の段落ブロック、b のときプレーンテキストの段落ブロックを生成します ( デフォルトは b )。

random

random が与えられたとき、一般的な文章 ( "Lorem ipsum dolor sit amet..." ) を使わずにテキストを生成します。

例:

  • {% lorem %} は、一般的な "lorem ipsum" を出力します。

  • {% lorem 3 p %} は一般的な "lorem ipsum" と 2 個のランダムな文章を、それぞれ HTML の <p> タグで括って出力します。

  • {% lorem 2 w random %} は 2 個のランダムなラテン単語を出力します。

nowLink to this heading

指定したフォーマット文字列にしたがって現在の日付や時刻を表示します。フォーマット文字列で使われる文字については、 date フィルタの項で説明しています。

Example:

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

Note that you can backslash-escape a format string if you want to use the "raw" value. In this example, both "o" and "f" are backslash-escaped, because otherwise each is a format string that displays the year and the time, respectively:

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

この表示結果は "It is the 4th of September" となります。

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 blocktranslate for example:

Django template
{% now "Y" as current_year %}
{% blocktranslate %}Copyright {{ current_year }}{% endblocktranslate %}

regroupLink to this heading

オブジェクトのリストから、同じ属性値を持つオブジェクトのグループを作ります。

この複雑なタグは例を通して説明するのがいいでしょう: cities"name", "population", and "country" をキーとして含むディクショナリによって表された都市のリストとします:

Python
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"},
]

...そして、あなたは次のように、国別に並べた一覧を表示させたいものとしましょう:

  • India

    • Mumbai: 19,000,000

    • Calcutta: 15,000,000

  • USA

    • New York: 20,000,000

    • Chicago: 7,000,000

  • Japan

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

Django template
{% 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>

順に追ってみましょう。{% regroup %} タグは 3 つの引数を持ちます:  グループ分けを行うリスト、グループ分けに使う属性の名前、そして結果とするリストの名前の 3 つです。ここでは cities リストを country 属性を使ってグループに分け、その結果を country_list と呼ぶことにしています。

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

  • grouper -- グループ分けに使われた要素 ( ここでは "India" "Japan" といった文字列 )

  • list -- このグループ内のすべての要素からなるリスト ( たとえば country='India' であるすべての都市のリスト)

Because {% regroup %} produces namedtuple() objects, you can also write the previous example as:

Django template
{% 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>

{% regroup %} は入力をソートしないことに注意してください! 上の例では、 リスト cities は、あらかじめ country の順でソート済みだという前提です。 citiescountry の順に並べられて いなかった 場合、 regroup はそのまま何も考えずに 1 つの国に対してグループを 1 つ以上作ってしまうかもしれません。例えばリスト cities が、次のように ( リスト内で国ごとにまとまっていない状態に ) なっていたとしましょう:

Python
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"},
]

この cities を入力に使うと、先ほどの {% regroup %} テンプレートコードは次のような結果を出力するでしょう:

  • India

    • Mumbai: 19,000,000

  • USA

    • New York: 20,000,000

  • India

    • Calcutta: 15,000,000

  • USA

    • Chicago: 7,000,000

  • Japan

    • Tokyo: 33,000,000

このような落し穴を解決するには、ビューコード内であらかじめデータを表示したい順番に並べておくのが最も簡単でしょう。

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

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

その他の属性によるグループ化Link to this heading

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:

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

Or, if country is a field with choices, it will have a get_FOO_display() method available as an attribute, allowing you to group on the display string rather than the choices key:

Django template
{% regroup cities by get_country_display as country_list %}

このとき {{ country.grouper }}choices の辞書から、キーではなく値のフィールドを表示することでしょう。

resetcycleLink to this heading

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.

Example usage:

Django template
{% 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 %}

This example would return this HTML:

Html
<h1>Gareth</h1>
<p class="odd">Harry</p>
<p class="even">John</p>
<p class="odd">Nick</p>

<h1>John</h1>
<p class="odd">Andrea</p>
<p class="even">Melissa</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".

You can also reset named cycle tags:

Django template
{% 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.

spacelessLink to this heading

ブロック内の HTML タグ間にある空白文字を除去します。タブ文字や改行も含みます。

Example usage:

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

This example would return this HTML:

Django template
<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:

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

templatetagLink to this heading

テンプレートタグの構文で使われる文字を、通常の文字として出力します。

The template system has no concept of "escaping" individual characters. However, you can use the {% templatetag %} tag to display one of the template tag character combinations.

どの要素を出力するかは、引数で指定します:

Argument

出力

openblock

{%

closeblock

%}

openvariable

{{

closevariable

}}

openbrace

{

closebrace

}

opencomment

{#

closecomment

#}

Sample usage:

Django template
The {% templatetag openblock %} characters open a block.

See also the verbatim tag for another way of including these characters.

urlLink to this heading

ビューとオプションの引数を指定して、これとマッチする絶対パスへの参照 ( ドメイン部分を除いた URL ) を返します。結果のパスに特殊文字が含まれる場合、 iri_to_uri() を使ってエンコードされます。

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

Django template
{% 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:

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

1 つの呼び出しのなかで、固定引数とキーワード引数を混ぜることはできません。また URLconf で必要とされる引数はすべて指定しなければなりません。

例えば app_views.client という名前のビューがあって、クライアントの ID を引数に取るとしましょう ( client() は、 views ファイル app_views.py の中で定義されているメソッドです ) 。 URLconf は以下のようなものになるでしょう:

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

このアプリケーションの URLconf が、プロジェクトの URLconf の中に次のような形で include されていたとします:

Python
path("clients/", include("project_name.app_name.urls"))

...then, in a template, you can create a link to this view like this:

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

テンプレートタグの出力は、文字列 /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:

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

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

`` ~ as 変数`` の構文で作られた変数は、 {% url %} タグのある {% block %} 内がスコープとなります。

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:

Django template
{% 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:

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

これは通常の namespaced URL resolution strategy に従います。ここには現在のアプリケーションに関してコンテキストから得られる様々なヒントについて書かれています。

verbatimLink to this heading

このブロックタグ内では、テンプレートエンジンによる解釈を行いません。

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

Django template
{% 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:

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

widthratioLink to this heading

バーチャートなどを生成する場合のために、指定した値と最大値との比を計算し、 定数に掛けた値を返します。

例えば:

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

ここで this_value = 175 、 max_value = 200 であるとき、画像の幅は 88 ピクセルになります (175 / 200 = .875、 .875 * 100 = 87.5 から四捨五入して 88 )。

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

Django template
{% widthratio this_value max_value max_width as width %}
{% blocktranslate %}The width is: {{ width }}{% endblocktranslate %}

withLink to this heading

複雑な表現の変数の値をキャッシュし、簡単な名前で参照できるようにします。呼出しコストの高いメソッド (例えばデータベースを操作するようなメソッド) に何度もアクセスする際に便利です。

例えば:

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

値を組み込んだ変数 (上の例でいえば total ) は {% with %}{% endwith %} タグの間でだけ有効です。

You can assign more than one context variable:

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

組み込みフィルタリファレンスLink to this heading

addLink to this heading

入力値に対して引数の値を加算します。

例えば:

Django template
{{ value|add:"2" }}

value が 4 なら、出力は 6 になるでしょう。

このフィルタは、まず両方の値を強制的に整数とみなして加算しようとします。失敗した場合は、とにかく値を足し合わせることを試みます。これはいくつかのデータ型 (文字列、リストなど) では動作しますが、それ以外では失敗します。失敗した場合、結果は空の文字列になります。

For example, if we have:

Django template
{{ first|add:second }}

first[1, 2, 3]second[4, 5, 6] であった場合、出力は [1, 2, 3, 4, 5, 6] になります。

addslashesLink to this heading

引用符の前にスラッシュを追加します。CSV などの文字列をエスケープする際に便利です。

例えば:

Django template
{{ value|addslashes }}

value の値が "I'm using Django" のとき、出力は "I\'m using Django" となります。

capfirstLink to this heading

入力値の先頭の文字を大文字に変換します。最初の文字がアルファベットでなければ効果はありません。

例えば:

Django template
{{ value|capfirst }}

If value is "django", the output will be "Django".

centerLink to this heading

入力値を引数で指定された幅のフィールド内に中央寄せします。

例えば:

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

value の値が "django" のとき、出力は "     Django    " となります。

cutLink to this heading

入力値の中から、引数に指定した値を全て取り除きます。

例えば:

Django template
{{ value|cut:" " }}

value の値が "String with spaces" のとき、出力は "Stringwithspaces" となります。

dateLink to this heading

引数に指定した書式で日付をフォーマットします。

Uses a similar format to PHP's date() function with some differences.

利用可能なフォーマット文字:

フォーマット文字

説明

出力の例

Day

d

日。 2 桁のゼロ詰め表示です。

'01''31'

j

日。ゼロ埋め表示なし。

'1''31'

D

曜日。 アルファベット 3 文字のテキスト形式です。

'Fri'

l

曜日。長いテキスト形式です。

'Friday'

S

日を表わす数字につける、英語特有の接尾辞。アルファベット 2 文字です。

'st', 'nd', 'rd' or 'th'

w

曜日(数字 1 桁)。

'0' (日曜) ~ '6' (土曜)

z

日(1年間における)

1 to 366

Week

W

ISO-8601 による年間の週番号。 週は月曜日から始まります。

1, 53

Month

m

月。数字 2 桁で、ゼロ埋め表示します。

'01''12'

n

月。ゼロ埋め表示しません。

'1''12'

M

月。アルファベット 3 文字のテキスト形式です。

'Jan'

b

月。アルファベット(小文字) 3 文字のテキスト形式です。

'jan'

E

月。ロケールが定義する代替表現が使われ、通常は長いテキスト形式になります。

'listopada' ( ロケールがポーランド語の場合。ポーランド語 'Listopad( 11 月)' の、時制における変化形 )

F

月。長いテキスト形式で表したものです。

'January'

N

AP スタイルブックによる月の省略表記。独自の拡張です。

'Jan.', 'Feb.', 'March', 'May'

t

その月の日数。

2831

Year

y

Year, 2 digits with leading zeros.

'00' to '99'

Y

Year, 4 digits with leading zeros.

'0001', ..., '1999', ..., '9999'

L

うるう年かどうかを表すブール値です。

True または False

o

ISO-8601 の週番号付き記法による年。うるう週を用いた ISO-8601 週番号 (W) に対応します。一般的な年のフォーマットは Y を参照してください。

'1999'

Time

g

時( 12 時間表記)。ゼロ埋め表示なし。

'1''12'

G

時( 24 時間表記)。ゼロ埋め表示なし。

'0''23'

h

時( 12 時間表記)。

'01''12'

H

時( 24 時間表記)。

'00''23'

i

分。

'00''59'

s

秒。数字 2 桁で、ゼロ埋め表示です。

'00''59'

u

マイクロ秒。

000000999999

a

'a.m.' または 'p.m.' ( 注: PHP における出力と少し異なり、 AP スタイルブックに従ってピリオドをつけます )

'a.m.'

A

'AM' または 'PM'

'AM'

f

時と分(12 時間表記)。ただしゼロ分であるときは時間だけを表示します。これは独自の拡張です。

'1''12'

P

時刻。12 時間表記による 時間:分 に続けて ‘a.m.’ または ’p.m.’ を表示します。ゼロ分である場合には分の表示が省略され、必要に応じて ‘midnight’ または ‘noon’ の表示になります。 独自の拡張です。

'1 a.m.', '1:30 p.m.', 'midnight', 'noon', '12:30 p.m.'

Timezone

e

タイムゾーン名。どのフォーマットでも使えますが、 datetime によっては空の文字列を返す場合もあります。

'', 'GMT', '-500', 'US/Eastern' など

I

Daylight saving time, whether it's in effect or not.

'1' または '0'

O

グリニッジ標準時からの時差。

'+0200'

T

計算機のタイムゾーン設定。

'EST', 'MDT'

Z

タイムゾーンオフセットを秒であらわしたもの。UTC よりも西側のタイムゾーン値は全て負の値になり、東側の値は常に正になります。

-4320043200

Date/Time

c

ISO 8601 format. (Note: unlike other 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 、または datetime が naive である場合 2008-01-02T10:30:00.000123

r

RFC 5322 formatted date.

'Thu, 21 Dec 2000 16:01:07 +0200'

U

Unix エポック時 ( UTC 協定世界時 1970年1月1日 00:00:00 ) からの秒数。

例えば:

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

上の例で、値が datetime オブジェクトである場合 ( 例えば datetime.datetime.now() の結果など ) 、出力は 'Wed 09 Jan 2008' となります。

フォーマットには、プリセット( DATE_FORMAT, DATETIME_FORMAT, SHORT_DATE_FORMAT or SHORT_DATETIME_FORMAT )のうちの1つ、または上記の表で示したフォーマット指定文字を使ったカスタムフォーマットが使えます。プリセットのフォーマットは、現在のロケールに応じて表示が変化することに注意してください。

Assuming that USE_L10N is True and LANGUAGE_CODE is, for example, "es", then for:

Django template
{{ value|date:"SHORT_DATE_FORMAT" }}

上記の出力は、文字列 "09/01/2008" となります ( es ロケールの "SHORT_DATE_FORMAT" フォーマットは、 Django の初期設定では "d/m/Y" です)。

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

Django template
{{ 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'). Both "d" and "e" are backslash-escaped, because otherwise each is a format string that displays the day and the timezone name, respectively.

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

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

defaultLink to this heading

入力の評価値が False の場合、引数に指定したデフォルト値を使います。そうでなければ、入力値を使います。

例えば:

Django template
{{ value|default:"nothing" }}

value"" ( 空の文字列 ) のとき、出力は nothing になります。

default_if_noneLink to this heading

入力値が None であるとき ( None であるときのみ ) 、引数に指定したデフォルト値を使いま す。そうでなければ、入力値を使います。

空の文字列が入力された場合は、デフォルト値を 使わない ことに注意してください。空文字列をフォールバックしたければ default フィルタを使ってください。

例えば:

Django template
{{ value|default_if_none:"nothing" }}

If value is None, the output will be nothing.

dictsortLink to this heading

辞書のリストを入力として、引数に指定したキーでリストをソートして返します。

例えば:

Django template
{{ value|dictsort:"name" }}

value が以下の内容であるとします:

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

このとき出力は以下のようになるでしょう:

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

You can also do more complicated things like:

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

ここで books が以下の内容だとします:

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

このとき出力は以下のようになるでしょう:

Django template
* 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:

Django template
{{ value|dictsort:0 }}

value が以下の内容であるとします:

Python
[
    ("a", "42"),
    ("c", "string"),
    ("b", "foo"),
]

このとき出力は以下のようになるでしょう:

Python
[
    ("a", "42"),
    ("b", "foo"),
    ("c", "string"),
]

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

Django template
{{ values|dictsort:"0" }}

Ordering by elements at specified index is not supported on dictionaries.

dictsortreversedLink to this heading

辞書のリストを入力に取り、引数に指定したキーでリストを逆順にソートして返します。これは上のフィルタと全く同じ処理をしますが、返す値は逆順です。

divisiblebyLink to this heading

値が引数の値で割り切れる場合に True を返します。

例えば:

Django template
{{ value|divisibleby:"3" }}

value21 であるとき、出力は True です。

escapeLink to this heading

入力文字中にある HTML の特殊文字をエスケープします。具体的には、以下のような置換を行います:

  • <&lt; に変換

  • >&gt; に変換

  • ' (single quote) is converted to &#x27;

  • " ( ダブルクォート ) を &quot; に変換

  • &&amp; に変換

escape を変数に適用するとき、変数にはすでに自動エスケープが適用されているかもしれませんが、エスケープが二重に実行されることはありません。したがって自動エスケープ環境であっても、この機能は安全に使用できます。複数回のエスケープが適用されるようにしたい場合は force_escape フィルターを使用してください。

For example, you can apply escape to fields when autoescape is off:

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

escapejsLink to this heading

Escapes characters for use as a whole JavaScript string literal, within single or double quotes, as below. This filter does not make the string safe for use in "JavaScript template literals" (the JavaScript backtick syntax). Any other uses not listed above are not supported. It is generally recommended that data should be passed using HTML data- attributes, or the json_script filter, rather than in embedded JavaScript.

例えば:

Django template
<script>
let myValue = '{{ value|escapejs }}'

filesizeformatLink to this heading

入力値を、人間が読みやすいファイルサイズ表現 ('13 KB', '4.1 MB', '102 bytes' など) に変換します。

例えば:

Django template
{{ value|filesizeformat }}

value が 123456789 のとき、出力は 117.7 MB になります。

firstLink to this heading

リスト中の最初の要素を返します。

例えば:

Django template
{{ value|first }}

value がリスト ['a', 'b', 'c'] であるとき、出力は 'a' になります。

floatformatLink to this heading

引数なしで使った場合、浮動小数点数を小数点以下1桁に丸めます。ただし小数部分がない時には整数部分だけを表示します。例を示します:

value

テンプレート

出力

34.23234

{{ value|floatformat }}

34.2

34.00000

{{ value|floatformat }}

34

34.26000

{{ value|floatformat }}

34.3

引数に1以上の整数を指定した場合、 floatformat は小数部分を指定された桁数で丸めます。以下に例を示します:

value

テンプレート

出力

34.23234

{{ value|floatformat:3 }}

34.232

34.00000

{{ value|floatformat:3 }}

34.000

34.26000

{{ value|floatformat:3 }}

34.260

特に便利な使い方として、引数に 0 (ゼロ) を指定した場合、入力値を一番近い整数に丸めます。

value

テンプレート

出力

34.23234

{{ value|floatformat:"0" }}

34

34.00000

{{ value|floatformat:"0" }}

34

39.56000

{{ value|floatformat:"0" }}

40

引数に負の数を指定した場合、小数部分を指定された桁数(指定された数の絶対値)で丸めます。ただし小数部分がない時には整数部分だけを表示します。例を示します:

value

テンプレート

出力

34.23234

{{ value|floatformat:"-3" }}

34.232

34.00000

{{ value|floatformat:"-3" }}

34

34.26000

{{ value|floatformat:"-3" }}

34.260

If the argument passed to floatformat has the g suffix, it will force grouping by the THOUSAND_SEPARATOR for the active locale. For example, when the active locale is en (English):

value

テンプレート

出力

34232.34

{{ value|floatformat:"2g" }}

34,232.34

34232.06

{{ value|floatformat:"g" }}

34,232.1

34232.00

{{ value|floatformat:"-3g" }}

34,232

Output is always localized (independently of the {% localize off %} tag) unless the argument passed to floatformat has the u suffix, which will force disabling localization. For example, when the active locale is pl (Polish):

value

テンプレート

出力

34.23234

{{ value|floatformat:"3" }}

34,232

34.23234

{{ value|floatformat:"3u" }}

34.232

floatformat を引数なしで使用した場合の動作は、引数に -1 を指定した場合と同じです。

force_escapeLink to this heading

文字列に HTML エスケープを適用します。 ( 詳しくは escape フィルタを参照してください )。フィルタは 即座に 適用され、新たなエスケープ済みの文字列を返します。このタグが有用となるケースは稀で、複数回のエスケープが必要な場合や、エスケープされた結果に対して他のフィルタを適用したい場合に使います。通常は escape フィルタを使うことになるでしょう。

For example, if you want to catch the <p> HTML elements created by the linebreaks filter:

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

get_digitLink to this heading

入力値が整数であるとき、引数で指定された桁にある数字を返します。例えば引数が 1 のとき右端の桁、 2 のとき右から 2 桁目が指定されます。入力が整数でない場合には、入力値をそのまま返します。

例えば:

Django template
{{ value|get_digit:"2" }}

value123456789 のとき、出力は 8 です。

iriencodeLink to this heading

IRI (国際化リソース識別子 Internationalized Resource Identifier) を URL に適した文字列に変換します。これは非 ASCII 文字列を URL に埋め込む場合に必要なフィルタです。

urlencode フィルタを通した後の文字列を、このフィルタに通しても問題はありません。

例えば:

Django template
{{ value|iriencode }}

value の値が "?test=1&me=2" のとき、出力は "?test=1&amp;me=2" になります。

joinLink to this heading

Python の str.join(list) と同じく、リストを文字列でつなぎます。

例えば:

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

value の値がリスト ['a', 'b', 'c'] であるとき、出力は文字列 "a // b // c" となります。

json_scriptLink to this heading

Safely outputs a Python object as JSON, wrapped in a <script> tag, ready for use with JavaScript.

Argument: The optional HTML "id" of the <script> tag.

例えば:

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

If value is the dictionary {'hello': 'world'}, the output will be:

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

The resulting data can be accessed in JavaScript like this:

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

XSS attacks are mitigated by escaping the characters "<", ">" and "&". For example if value is {'hello': 'world</script>&amp;'}, the output is:

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

lastLink to this heading

リストの末尾の要素を返します。

例えば:

Django template
{{ value|last }}

value の値がリスト ['a', 'b', 'c', 'd'] のとき、出力は文字列 "d" です。

lengthLink to this heading

入力値の長さを返します。これは、文字列とリストの両方で動作します。

例えば:

Django template
{{ value|length }}

value['a', 'b', 'c', 'd']"abcd" であるとき、それぞれ出力は 4 になります。

The filter returns 0 for an undefined variable.

length_isLink to this heading

入力値の長さと引数が等しければ True を返し、そうでなければ False を返します。

例えば:

Django template
{{ value|length_is:"4" }}

value['a', 'b', 'c', 'd'] あるいは "abcd" であるとき、それぞれ出力は True です。

linebreaksLink to this heading

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

例えば:

Django template
{{ value|linebreaks }}

If value is Joel\nis a slug, the output will be <p>Joel<br>is a slug</p>.

linebreaksbrLink to this heading

Converts all newlines in a piece of plain text to HTML line breaks (<br>).

例えば:

Django template
{{ value|linebreaksbr }}

If value is Joel\nis a slug, the output will be Joel<br>is a slug.

linenumbersLink to this heading

テキストを行番号付きで表示します。

例えば:

Django template
{{ value|linenumbers }}

value が以下の内容であるとします:

Django template
one
two
three

the output will be:

Django template
1. one
2. two
3. three

ljustLink to this heading

入力値を指定した幅のフィールド内で左詰めします。

引数: フィールドの幅

例えば:

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

valueDjango であるとき、出力は "Django    " となります。

lowerLink to this heading

文字列を全て小文字に変換します。

例えば:

Django template
{{ value|lower }}

valueTotally LOVING this Album! であるとき、出力は totally loving this album! となります。

make_listLink to this heading

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.

例えば:

Django template
{{ value|make_list }}

value の値が文字列 "Joel" であるとき、出力はリスト ['J', 'o', 'e', 'l'] です。 value123 のとき、出力はリスト ['1', '2', '3'] となります。

phone2numericLink to this heading

電話番号 (文字を含む場合もあります) を数値だけの番号に変換します。

入力値は正しい電話番号でなくてもかまいません。このフィルタはどんな文字列でも変換します。

例えば:

Django template
{{ value|phone2numeric }}

value800-COLLECT のとき、出力は 800-2655328 となります。

pluralizeLink to this heading

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

Example:

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

num_messages1 のとき、出力は You have 1 message. です。 num_messages2 のとき、出力は You have 2 messages. となります。

's' 以外の接尾辞が必要な場合は、代わりの接尾辞をフィルタの引数で指定できます。

Example:

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

単純な接尾辞では複数形にできない単語の場合、単数形と複数形の接尾辞の両方をコンマで区切って指定できます。

Example:

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

pprintLink to this heading

pprint.pprint() のラッパーです -– 実のところ、これはデバッグ用です。

randomLink to this heading

与えられたリストからランダムな要素を返します。

例えば:

Django template
{{ value|random }}

value の値がリスト ['a', 'b', 'c', 'd'] であるとき、出力は "b" かもしれません。

rjustLink to this heading

入力値を指定した幅のフィールド内で右詰めします。

引数: フィールドの幅

例えば:

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

valueDjango であるとき、出力は "    Django" となります。

safeLink to this heading

文字列に対して、さらなる HTML エスケープが必要でないことをマークするのに使います。 autoescaping がオフの場合、このフィルタは何もしません。

safeseqLink to this heading

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:

Django template
{{ some_list|safeseq|join:", " }}

この場合、直接 safe フィルタを使用すると正しく動作しないかもしれません。シーケンスの個々の要素に対して作用するのではなく、まず変数を文字列に変換して処理するからです。

sliceLink to this heading

リストに対するスライスを返します。

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

Example:

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

some_list['a', 'b', 'c'] ならば、出力は ['a', 'b'] となります。

slugifyLink to this heading

ASCIIに変換します。スペースをハイフ​​ンに変換します。英数字以外の文字、アンダースコア、ハイフンは削除します。小文字に変換します。また、先頭と末尾の空白を取り除きます。

例えば:

Django template
{{ value|slugify }}

value"Joel is a slug" であるとき、出力は "joel-is-a-slug" となります。

stringformatLink to this heading

引数 (表示形式を指定する文字列) に応じて、変数の表示形式を変更します。指定方法には、printf-style String Formatting シンタックスを使います。例外として、最初の ''%'' は無視されます。

例えば:

Django template
{{ value|stringformat:"E" }}

例えば value10 の場合、出力は 1.000000E+01 となります。

striptagsLink to this heading

[X]HTML タグを全てはぎとるようにします。

例えば:

Django template
{{ value|striptags }}

value"<b>Joel</b> <button>is</button> a <span>slug</span>" であるとき、出力は "Joel is a slug" となります。

timeLink to this heading

時刻を指定の書式にしたがってフォーマットします。

フォーマットは date と同様に、あらかじめ定義された TIME_FORMAT のプリセット、またはカスタムフォーマットを使うこともできます。この定義はロケールに依存することに注意してください。

例えば:

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

valuedatetime.datetime.now() の値であるとき、出力は "01:23" といった文字列になります。

Note that you can backslash-escape a format string if you want to use the "raw" value. In this example, both "h" and "m" are backslash-escaped, because otherwise each is a format string that displays the hour and the month, respectively:

Django template
{{ value|time:"H\h i\m" }}

This would display as "01h 23m".

その他の例:

Assuming that USE_L10N is True and LANGUAGE_CODE is, for example, "de", then for:

Django template
{{ 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. If you need to format a date value, use the date filter instead (or along with time if you need to render a full datetime value).

上記のルールにはひとつ例外があります。タイムゾーン情報つきの datetime の値 (a time-zone-aware datetime instance) を渡した場合、 time フィルタはタイムゾーン関連の format specifiers である 'e''O''T''Z' を受け付けます。

When used without a format string, the TIME_FORMAT format specifier is used:

Django template
{{ value|time }}

is the same as:

Django template
{{ value|time:"TIME_FORMAT" }}

timesinceLink to this heading

日付を経過時間の形式にフォーマットします (例えば、 “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":

Django template
{{ blog_date|timesince:comment_date }}

タイムゾーン情報を持たない値(offset-naive)と、タイムゾーン情報つき(offset-aware)の値とを比較した場合は、空の文字列を返します。

最小単位は "分" です。比較対象からみて未来にある日時に対しては "0 minutes" を返します。

timeuntilLink to this heading

timesince に似ていますが、現在時刻を起点として指定の日付または日時までの時刻を計算します。例えば今日が 2006年 6月 1日で conference_date が 2006年 6月 29日の値を保持する日付インスタンスだったとすれば、 {{ conference_date|timeuntil }} は "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":

Django template
{{ conference_date|timeuntil:from_date }}

タイムゾーン情報を持たない値(offset-naive)と、タイムゾーン情報つき(offset-aware)の値とを比較した場合は、空の文字列を返します。

最小単位は "分" です。比較対象からみて過去にある日時に対しては “0 minutes” を返します。

titleLink to this heading

文字列中の単語に対して、それぞれ先頭の文字を大文字に、残りを小文字にすることで文字列をタイトルケースに変換します。"主要でない単語" については小文字を維持できないこともあります。

例えば:

Django template
{{ value|title }}

value"my FIRST post" であるとき、出力は "My First Post" となります。

truncatecharsLink to this heading

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

引数: 切り詰める文字数

例えば:

Django template
{{ value|truncatechars:7 }}

value"Joel is a slug" であるとき、出力は "Joel i…" となります。

truncatechars_htmlLink to this heading

truncatechars に似ていますが、 HTML タグを認識します。切り詰めを行う時点で閉じていないタグがあれば、切り詰めた文字の直後に全て閉じます。

例えば:

Django template
{{ value|truncatechars_html:7 }}

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

HTML コンテンツ内の改行は保持されます。

truncatewordsLink to this heading

文字列を指定された単語数以内に切り詰めます。

引数: 切り詰めた後の単語数

例えば:

Django template
{{ value|truncatewords:2 }}

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

文字列中の改行は取り除かれます。

truncatewords_htmlLink to this heading

truncatewords に似ていますが、 HTML タグを認識します。切り詰めを行う時点で閉じていないタグがあれば、切り詰めた文字の直後に全て閉じます。

このタグの処理は truncatewords よりも効率が悪いため、 HTML テキストを 渡す場合にだけ使うようにしてください。

例えば:

Django template
{{ value|truncatewords_html:2 }}

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

HTML コンテンツ内の改行は保持されます。

unordered_listLink to this heading

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:

Django template
<li>States
<ul>
        <li>Kansas
        <ul>
                <li>Lawrence</li>
                <li>Topeka</li>
        </ul>
        </li>
        <li>Illinois</li>
</ul>
</li>

upperLink to this heading

入力値をすべて大文字に変換します。

例えば:

Django template
{{ value|upper }}

value"Joel is a slug" であるとき、出力は "JOEL IS A SLUG" となります。

urlencodeLink to this heading

入力値を URL で使えるようにエスケープします。

例えば:

Django template
{{ value|urlencode }}

value"https://www.example.org/foo?a=b&c=d" のとき、出力は "https%3A//www.example.org/foo%3Fa%3Db%26c%3Dd" となります。

オプションの引数で、エスケープさせない文字を指定できます。

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

Django template
{{ value|urlencode:"" }}

ここで value"https://www.example.org/" であるとき、出力は "https%3A%2F%2Fwww.example.org%2F" となります。

urlizeLink to this heading

テキスト内の URL と Email アドレスをクリック可能なリンクに変換します。

このテンプレートタグは http://https://www. で始まるリンクに作用します。例えば https://goo.gl/aia1t は変換されます。しかし goo.gl/aia1t はそのままです。

末尾が .com.edu.gov.int.mil.net.org である場合は、ドメイン名のみのリンクもサポートします。例えば djangoproject.com は変換されます。

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

urlize が生成したリンクにはアトリビュート rel="nofollow" が加えられています。

例えば:

Django template
{{ value|urlize }}

value"Check out www.djangoproject.com" であるとき、出力は "Check out <a href="http://www.djangoproject.com" rel="nofollow">www.djangoproject.com</a>" となります。

ウェブリンクに加えて、 urlize は email アドレスも mailto: リンクに変換できます。value"Send questions to foo@example.com" であるとき、出力は "Send questions to <a href="mailto:foo@example.com">foo@example.com</a>" となります。

urlize フィルタはオプションの引数 autoescape をとることができます。autoescapeTrue のとき、リンクテキストと URL は Django の組み込みフィルタ escape でエスケープされます。指定しない場合の autoescape の値は True です。

urlizetruncLink to this heading

urlize と同じように、URL と email アドレスをクリック可能なリンクに変換します。ただし、指定の文字数以上の表示を切り詰めます。

引数: URL を切り詰める長さ。省略記号の長さを含みます。省略記号は省略が必要な場合につけられます。

例えば:

Django template
{{ value|urlizetrunc:15 }}

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

urlize と同じく、このフィルタはプレーンテキストに対してだけ使ってください。

wordcountLink to this heading

ワード数を返します。

例えば:

Django template
{{ value|wordcount }}

value"Joel is a slug" のとき、出力は 4 です。

wordwrapLink to this heading

指定した行幅でワードラップします。

引数: テキストをラップするまでのワード数

例えば:

Django template
{{ value|wordwrap:5 }}

If value is Joel is a slug, the output would be:

Django template
Joel
is a
slug

yesnoLink to this heading

入力値 ( "True" 、 "False" 、オプションで "None" ) に対応する文字列を返します。対応する文字列はデフォルトでは "yes"、"no"、"maybe" です。またコンマ区切りの文字列を引数として与えることでカスタムマッピングを指定できます。

例えば:

Django template
{{ value|yesno:"yeah,no,maybe" }}

Argument

出力

True

yes

True

"yeah,no,maybe"

yeah

False

"yeah,no,maybe"

no

None

"yeah,no,maybe"

maybe

None

"yeah,no"

no (None に対応する値がない場合は False の値が使われます)

国際化タグとフィルタLink to this heading

Django はテンプレートの internationalization をそれぞれの角度から制御するタグやフィルタを提供し、翻訳、書式設定、およびタイムゾーン変換のきめ細かい制御を可能にしています。

i18nLink to this heading

このライブラリは、テンプレート内の飜訳可能なテキストを指定することができます。これを有効化するには USE_I18NTrue に設定し、 {% load i18n %} でロードします。

ローカル化: テンプレート内 も参照してください。

l10nLink to this heading

このライブラリは、テンプレート内の値のローカライズを制御します。必要なのは {% load l10n %} でライブラリをロードすることだけですが、ローカライズをデフォルトで有効にするため USE_L10NTrue に設定する場合もしばしばあるでしょう。

テンプレート内でローカル化をコントロールする も参照してください。

tzLink to this heading

このライブラリは、テンプレートのタイムゾーン変換を制御します。 l10n と同じく、必要なのは {% load tz %} を使ってライブラリをロードするだけですが、通常はデフォルトでローカル時間に変換されるよう、 USE_TZTrue に設定するでしょう。

テンプレートでのタイムゾーン aware な出力 も参照してください。

その他のタグとフィルタライブラリLink to this heading

この他にも、Django にはいくつかのテンプレートタグ・ライブラリがあります。これらのライブラリは INSTALLED_APPS 設定で明示的に有効化したうえ、 {% load %} タグを使ってテンプレート上にロードする必要があります。

django.contrib.humanizeLink to this heading

データを「ヒトにやさしい」表現にする上で便利な Django テンプレートフィルタのセットです。くわしくは django.contrib.humanize を参照してください。

staticLink to this heading

staticLink to this heading

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

Django template
{% 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:

Django template
{% load static %}
<link rel="stylesheet" href="{% static user_stylesheet %}" media="screen">

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

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

get_static_prefixLink to this heading

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:

Django template
{% 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:

Django template
{% 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_prefixLink to this heading

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

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

値をデータ・アトリビュートに格納することにより、これを JavaScript コンテキスト内で使用したい場合に適切なエスケープがなされていることが保証されます。