0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Django2におけるカスタムテーンプレートタグ(フィルタ)の設定方法

Posted at

実行環境

python=3.8.2
Django=2.2.5
PC = Mac(catalina)

フォルダ作成

ここではアプリ名が__'myapp'__であると仮定します。

まずアプリ内にtemplatetagsフォルダを作り、
その中に__init__.pyと任意のカスタムフィルタファイル(ここではcalc.py)を作る。
ただし、__init__.pyには何も書かなくて大丈夫です。

myapp/
    __init__.py
    models.py
    templatetags/
        __init__.py
        calc.py
    views.py

テンプレートフィルタ作成

次にいcalc.pyにテンプレートフィルタを作っていきます。
テンプレートフィルタでは1つか2つの引数を受け取ることができます。

今回は与えられた数を2倍にするという簡単なテンプレートフィルタを作成します。

calc.py
from django import template

register = template.Library()

@register.filter
def multiply(value1):
    return value1 * 2

setting.pyの変更

setting.pyの変更も行っていきます。
次のようにsettings.pyを変更してください。

settings,py
INSTALLED_APPS = [
    ・・・
    'myapp',
    'myapp.templatetags.calc', {% <- ここを追加 %}
]

settings,py

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [TEMPLATE_DIR, ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
            'libraries': { 
                'markdown': 'myapp.templatetags.calc', {% <- ここを追加 %}
            }
        },
    },
]

テンプレートファイルでカスタムフィルタを適用

最後に、templateファイルに{% load ファイル名 %}を追加することで、
カスタムテンプレートフィルタを使えるようになります。


{% load calc %}

<!-- num1=3のとき、HTML上には6が表示される -->
<span>掛け算:{{ num1 | multiply }}</span>

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?