Django在模版中直接访问字典数据

问题场景

在模版中要遍历字典(dict),一般使用如下代码实现

{% for key,value in param.items %} 
    {{ key }}
    {{ value }}
{% endfor %}

但如果想直接访问的话,通过如下面方法获取是不可行的。需要使用自定义模版过滤器来实现。

{{ param.key }} #错误方法

创建自定义过滤器

  1. 在app目录新建templatetags目录,添加__init__.py 文件
  2. 修改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',

        }
    },
}]
  1. 添加过滤器方法,在templatetags 新建py文件,添加过滤器实现方法
# base.py
from django import template
register = template.Library()

@register.filter
def get_item(dictionary, key):
    return dictionary.get(key)

使用过滤器

  1. 在模版文件加载自定义过滤
{% load base %}
  1. 调用自定义过滤器
# 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" }}
  1. 检查结果
    在这里插入图片描述
  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值