Home > Backend Development > Python Tutorial > Django custom filter example

Django custom filter example

高洛峰
Release: 2016-10-17 14:06:04
Original
1116 people have browsed it

Requirements: Get the value from the dictionary by key, such as test[key]=value

views.py

from django.template import RequestContext
from django.shortcuts import render_to_response
def view(request)
    dicts = {"key1": 1, "key2": 2, "key3": 3, }
    return render_to_response("index.html",  {"dicts":dicts,},context_instance = RequestContext(request))
Copy after login

1. Create templatetags in the app directory/Create an empty file __init__ in this directory .py and myfilter.py

2. Edit

from django import template
register = template.Library()
def key(d,key_name):
        value = 0
        try:
                value = d[key_name]
        except KeyError:
                value = 0
        return value
register.filter('key',key)
Copy after login

in myfilter.py

3. Use

{% load myfilter %} #加载自定认标签
{{dicts|key:"key1"}}
Copy after login


in the template
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template