組み込みタグとフィルタ

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

組み込みタグリファレンス

autoescape

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

Sample usage:

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

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

block

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

comment

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

Sample usage:

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

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

cycle

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

This tag is particularly useful in a loop:

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

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

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

You can mix variables and strings:

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

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

would output:

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

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

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

debug

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

Changed in Django 2.2.27:

In older versions, debugging information was displayed when the DEBUG setting was False.

extends

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

このタグには 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:

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

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

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

filter

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

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

Sample usage:

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

注釈

escapesafe フィルタは引数として与えることができません。ブロックの自動エスケープを管理するには、代わりに autoescape タグを使ってください。

firstof

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:

{% firstof var1 var2 var3 %}

This is equivalent to:

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

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

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

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

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>

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

ドット演算子を使う場合、メソッドよりも辞書キーへの参照が優先することに注意してください。したがって、もしも 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 ... 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>

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

<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 %}

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

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

論理演算子

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

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

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

if (athlete_list and coach_list) or cheerleader_list

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

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

== 演算子

Equality. Example:

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

Inequality. Example:

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

Less than. Example:

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

Greater than. Example:

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

Less than or equal to. Example:

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

Greater than or equal to. Example:

{% if somevar >= 1 %}
  This appears if variable somevar is greater than 1 or equal to 1.
{% endif %}
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 %}
not in 演算子

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

is 演算子

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

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

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

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

フィルター

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

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

複雑な表現

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

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

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

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

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

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

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

you should use:

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

ifchanged

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

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

    <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

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

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

This example includes the contents of the template "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.

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

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

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

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

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

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

注釈

include タグの実行は『サブテンプレートを出力し、その結果である HTML を取り込む』と考えるべきで、『サブテンプレートを解析し、親テンプレートの一部分として、そこに組み込まれている』かのように考えるべきではありません。これは、取り込んだテンプレートの間では状態を共有できず、まったく独立した過程で出力されることを意味します。

ブロックは取り込まれる 前に 評価されます。ブロックを含んでいる他のテンプレートを取り込む場合、そのブロックは『 すでに評価され、出力された結果 』としてのブロックであり、例えばテンプレートを継承したときのような、オーバーライド可能なブロックではありません。

load

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

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 %}

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

lorem

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

Usage:

{% 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 個のランダムなラテン単語を出力します。

now

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

Example:

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:

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

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

注釈

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 表示形式のローカル化 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 blocktranslate for example:

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

regroup

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

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

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:

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

{% 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 が、次のように ( リスト内で国ごとにまとまっていない状態に ) なっていたとしましょう:

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:

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

その他の属性によるグループ化

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 %}

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:

{% regroup cities by get_country_display as country_list %}

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

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.

Example usage:

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

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

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

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

Example usage:

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

This example would return this HTML:

<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

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

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:

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

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

url

ビューとオプションの引数を指定して、これとマッチする絶対パスへの参照 ( ドメイン部分を除いた 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:

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

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

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

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

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

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

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

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

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

{% 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' %}

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

警告

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

verbatim

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

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

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

例えば:

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

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

with

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

例えば:

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

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

You can assign more than one context variable:

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

注釈

従来の冗長な書式もサポートされています: {% with business.employees.count as total %}

組み込みフィルタリファレンス

add

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

例えば:

{{ value|add:"2" }}

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

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

For example, if we have:

{{ first|add:second }}

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

警告

整数に変換可能な文字列は、整数として「加算」されます。上の例のように「結合」されません。

addslashes

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

例えば:

{{ value|addslashes }}

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

capfirst

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

例えば:

{{ value|capfirst }}

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

center

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

例えば:

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

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

cut

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

例えば:

{{ value|cut:" " }}

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

date

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

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

注釈

これらのフォーマット文字は、テンプレート以外では使えません。デザイナーが PHP のテンプレートから容易に変換できるように互換性を持たせています。

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

フォーマット文字 説明 出力の例
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 ) からの秒数。  

例えば:

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

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

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

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

default

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

例えば:

{{ value|default:"nothing" }}

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

default_if_none

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

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

例えば:

{{ value|default_if_none:"nothing" }}

If value is None, the output will be nothing.

dictsort

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

例えば:

{{ value|dictsort:"name" }}

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

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

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

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

You can also do more complicated things like:

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

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

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

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

* 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 }}

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

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

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

[
    ("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" }}

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

Changed in Django 2.2.26:

In older versions, ordering elements at specified index was supported on dictionaries.

dictsortreversed

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

divisibleby

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

例えば:

{{ value|divisibleby:"3" }}

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

escape

入力文字中にある 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:

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

Chaining escape with other filters

As mentioned in the autoescape section, when filters including escape are chained together, it can result in unexpected outcomes if preceding filters mark a potentially unsafe string as safe due to the lack of escaping caused by autoescape being off.

In such cases, chaining escape would not reescape strings that have already been marked as safe.

escapejs

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.

例えば:

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

filesizeformat

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

例えば:

{{ value|filesizeformat }}

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

ファイルサイズと国際単位系(SI)

filesizeformat は、厳密には国際単位系(SI)に準拠していません。国際単位系ではバイトサイズを 1024 の累乗で計算する場合 (上の例がそうですが) 、 KiB、MiB、GiB などの単位を使うよう推奨しています。しかし Django ではより一般的な表記に対応して、従来の単位名( KB、 MB、GB など)を使用しています。

first

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

例えば:

{{ value|first }}

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

floatformat

引数なしで使った場合、浮動小数点数を小数点以下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_escape

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

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

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

get_digit

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

例えば:

{{ value|get_digit:"2" }}

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

iriencode

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

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

例えば:

{{ value|iriencode }}

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

join

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

例えば:

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

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

json_script

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.

例えば:

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

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

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

The resulting data can be accessed in JavaScript like this:

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:

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

Changed in Django 4.1:

In older versions, the HTML "id" was a required argument.

last

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

例えば:

{{ value|last }}

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

length

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

例えば:

{{ value|length }}

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

The filter returns 0 for an undefined variable.

length_is

バージョン 4.2 で非推奨.

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

例えば:

{{ value|length_is:"4" }}

value['a', 'b', 'c', 'd'] あるいは "abcd" であるとき、それぞれ出力は 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>).

例えば:

{{ value|linebreaks }}

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

linebreaksbr

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

例えば:

{{ value|linebreaksbr }}

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

linenumbers

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

例えば:

{{ value|linenumbers }}

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

one
two
three

the output will be:

1. one
2. two
3. three

ljust

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

引数: フィールドの幅

例えば:

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

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

lower

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

例えば:

{{ value|lower }}

valueTotally LOVING this Album! であるとき、出力は 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.

例えば:

{{ value|make_list }}

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

phone2numeric

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

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

例えば:

{{ value|phone2numeric }}

value800-COLLECT のとき、出力は 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'.

Example:

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

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

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

Example:

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

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

Example:

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

注釈

Use blocktranslate to pluralize translated strings.

pprint

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

random

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

例えば:

{{ value|random }}

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

rjust

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

引数: フィールドの幅

例えば:

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

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

safe

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

注釈

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:", " }}

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

slice

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

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

Example:

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

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

slugify

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

例えば:

{{ value|slugify }}

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

stringformat

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

例えば:

{{ value|stringformat:"E" }}

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

striptags

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

例えば:

{{ value|striptags }}

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

安全性の保証はありません

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, consider using a third-party HTML sanitizing tool.

time

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

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

例えば:

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

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

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

{{ value|time }}

is the same as:

{{ value|time:"TIME_FORMAT" }}

timesince

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

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

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

timeuntil

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

{{ conference_date|timeuntil:from_date }}

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

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

title

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

例えば:

{{ value|title }}

value"my FIRST post" であるとき、出力は "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 ("…").

引数: 切り詰める文字数

例えば:

{{ value|truncatechars:7 }}

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

truncatechars_html

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

例えば:

{{ value|truncatechars_html:7 }}

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

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

Size of input string

Processing large, potentially malformed HTML strings can be resource-intensive and impact service performance. truncatechars_html limits input to the first five million characters.

Changed in Django 3.2.22:

In older versions, strings over five million characters were processed.

truncatewords

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

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

例えば:

{{ value|truncatewords:2 }}

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

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

truncatewords_html

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

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

例えば:

{{ value|truncatewords_html:2 }}

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

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

Size of input string

Processing large, potentially malformed HTML strings can be resource-intensive and impact service performance. truncatewords_html limits input to the first five million characters.

Changed in Django 3.2.22:

In older versions, strings over five million characters were processed.

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

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

例えば:

{{ value|upper }}

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

urlencode

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

例えば:

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

{{ value|urlencode:"" }}

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

urlize

テキスト内の 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" が加えられています。

例えば:

{{ 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 です。

注釈

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

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

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

例えば:

{{ 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 と同じく、このフィルタはプレーンテキストに対してだけ使ってください。

wordcount

ワード数を返します。

例えば:

{{ value|wordcount }}

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

wordwrap

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

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

例えば:

{{ value|wordwrap:5 }}

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

Joel
is a
slug

yesno

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

例えば:

{{ 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 の値が使われます)

国際化タグとフィルタ

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

i18n

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

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

l10n

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

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

tz

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

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

その他のタグとフィルタライブラリ

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

django.contrib.humanize

データを「ヒトにやさしい」表現にする上で便利な Django テンプレートフィルタのセットです。くわしくは 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 in STORAGES. 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 %}" 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 }}">

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 %}">

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