Search code examples
djangotemplatetags

Dynamic dictionary name in templatetag


I have a templatetag to get the dictionary name and the element in it. I have the dictionaries in dictionary.py and I've imported the same as dict in the templatetag. Like this,

import property.dictionary as dict

def getlisttype(value,arg):
    return dict.value[arg]

I'm passing the dictionary name as value and the element in it as arg. But what I'm getting is an error saying no 'value' in dictionary. Is there a way to do this?

dictionary.py

list_type_dict={
1:"Sale",
2:"Rent"
}

list_category_dict={
1:"Residential",
2:"Commercial"
}
.
.
.

Solution

  • You can use __dict__ which is a dictionary of all attributes in a module, i.e.:

    import property.dictionary
    
    def getlisttype(value, arg):
        return property.dictionary.__dict__[value][arg]
    

    It is not a good idea to import your module as dict since that will cause a name conflict with the built in dict keyword.