问题场景
在模版中要遍历字典(dict),一般使用如下代码实现
{% for key,value in param.items %}
{{ key }}
{{ value }}
{% endfor %}
但如果想直接访问的话,通过如下面方法获取是不可行的。需要使用自定义模版过滤器来实现。
{{ param.key }} #错误方法
创建自定义过滤器
- 在app目录新建templatetags目录,添加__init__.py 文件
- 修改setting配置文件,在TEMPLATES增加如下libraries配置
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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',
'app.apptemplates.load_setting',
],
'libraries':{
'custom_templatetag': 'actualites.templatetags.mes_tags',
}
},
}]
- 添加过滤器方法,在templatetags 新建py文件,添加过滤器实现方法
# base.py
from django import template
register = template.Library()
@register.filter
def get_item(dictionary, key):
return dictionary.get(key)
使用过滤器
- 在模版文件加载自定义过滤
{% load base %}
- 调用自定义过滤器
# views.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render_to_response
def index(request):
param = {"test": {"param": 1}}
return render_to_response("index.html", {"parm": param})
# index.html
{% load base %}
{{ parm|get_item:"test" }}
- 检查结果