This article is a personal note when I first created an app in Django and looked for features like Rails helper.
Python(3.6.2) Django(2.1.7)
Rails helper can call the method defined in helper on the view side. In Django as well, I investigated whether the method defined in another file can be called on the template side, and it seems that it can be realized by creating a custom template filter.
You can create a custom template filter by following the steps below.
Create a directory called templatetags in the app directory of the template where you want to install the custom filter.
Place \ _ \ _ init__.py to modularize the files you create in the templatetags directory.
First call the template library.
from django import template
register = template.Library()
Register your own custom template filter in this library. Now you can call the method created on the template side.
@register.filter
def transrate_media_number(var):
if var == 0:
media_name = 'Gurunavi'
elif var == 1:
media_name = 'eating log'
elif var == 2:
media_name = 'Hot pepper'
else:
media_name = 'Other'
return media_name
custom_filter.py
from django import template
register = template.Library()
@register.filter
def transrate_media_number(var):
if var == 0:
media_name = 'Gurunavi'
elif var == 1:
media_name = 'eating log'
elif var == 2:
media_name = 'Hot pepper'
else:
media_name = 'Other'
return media_name
The end result is a directory structure like this:
app/ ├ models.py ├ templatetags/ │ ├ __init__.py │ └ custom_filter.py └ views.py
First, load the custom template filter created from the template.
- load custom_filter
The loaded custom template filter can be used in the following form.
{{argument|Custom template filter name}}
python:template_file.html.haml
- load custom_filter
%table
{% for data in datum %}
%tr
%td
{{ data.take_at }}
%td
# {{argument|Custom template filter name}}
{{ data.media_number | transrate_media_number }}
That's it.
Recommended Posts