Django template how to look up a dictionary value with a variable

后端 未结 8 1503
面向向阳花
面向向阳花 2020-11-22 03:06
mydict = {\"key1\":\"value1\", \"key2\":\"value2\"}

The regular way to lookup a dictionary value in a Django template is {{ mydict.key1 }}

8条回答
  •  既然无缘
    2020-11-22 03:19

    Environment: Django 2.2

    1. Example code:
    
    
        from django.template.defaulttags import register
    
        @register.filter(name='lookup')
        def lookup(value, arg):
            return value.get(arg)
    
    

    I put this code in a file named template_filters.py in my project folder named portfoliomgr

    1. No matter where you put your filter code, make sure you have __init__.py in that folder

    2. Add that file to libraries section in templates section in your projectfolder/settings.py file. For me, it is portfoliomgr/settings.py

    
    
        TEMPLATES = [
            {
                'BACKEND': 'django.template.backends.django.DjangoTemplates',
                'DIRS': [os.path.join(BASE_DIR, 'templates')],
                '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':{
                        'template_filters': 'portfoliomgr.template_filters',
                    }
                },
            },
        ]
    
    
    1. In your html code load the library

      
      {% load template_filters %}
      

提交回复
热议问题