【问题标题】:Dynamic dictionary name in templatetag模板标签中的动态字典名称
【发布时间】:2018-05-23 06:44:45
【问题描述】:

我有一个模板标签来获取字典名称和其中的元素。我在dictionary.py 中有字典,并且我在模板标签中导入了与字典相同的内容。像这样,

import property.dictionary as dict

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

我将字典名称作为值传递,将其中的元素作为 arg 传递。但我得到的是一个错误,说字典中没有“价值”。有没有办法做到这一点?

dictionary.py

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

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

【问题讨论】:

    标签: django templatetags


    【解决方案1】:

    您可以使用__dict__,它是模块中所有属性的字典,即:

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

    将模块导入为dict 不是一个好主意,因为这会导致与内置的dict 关键字发生名称冲突。

    【讨论】:

      猜你喜欢
      • 2019-10-27
      • 2019-02-02
      • 2012-01-04
      • 2021-10-14
      • 2013-05-06
      • 2021-11-10
      • 1970-01-01
      • 2013-11-14
      • 2022-01-23
      相关资源
      最近更新 更多