【问题标题】:How do I access dictionary keys that contain hyphens from within a Django template?如何从 Django 模板中访问包含连字符的字典键?
【发布时间】:2012-01-05 08:19:42
【问题描述】:

我们有一个建立在自定义数据库上的系统,其中许多属性的命名都包含连字符,即:

user-name
phone-number

这些属性无法在模板中访问,如下所示:

{{ user-name }}

Django 为此抛出异常。我想避免必须将所有键(和子表键)转换为使用下划线来解决这个问题。有没有更简单的方法?

【问题讨论】:

    标签: python django


    【解决方案1】:

    如果您不想重构对象,自定义模板标签可能是唯一的方法。对于使用任意字符串键访问字典,this question 的答案提供了一个很好的示例。

    对于懒人:

    from django import template
    register = template.Library()
    
    @register.simple_tag
    def dictKeyLookup(the_dict, key):
       # Try to fetch from the dict, and if it's not found return an empty string.
       return the_dict.get(key, '')
    

    你是这样使用的:

    {% dictKeyLookup your_dict_passed_into_context "phone-number" %}
    

    如果您想使用任意字符串名称访问对象的属性,您可以使用以下内容:

    from django import template
    register = template.Library()
    
    @register.simple_tag
    def attributeLookup(the_object, attribute_name):
       # Try to fetch from the object, and if it's not found return None.
       return getattr(the_object, attribute_name, None)
    

    您会使用如下:

    {% attributeLookup your_object_passed_into_context "phone-number" %}
    

    您甚至可以为子属性想出某种字符串分隔符(例如 '__'),但我会把它留作家庭作业 :-)

    【讨论】:

    • 我用过这个解决方案,但是把它从标签改成了过滤器。效果很好,谢谢!
    • 这绝对有效,但是如何访问包含字典作为值的字典内的键?
    【解决方案2】:

    不幸的是,我认为你可能不走运。来自docs

    变量名称必须由任意字母 (A-Z)、任意数字 (0-9)、 下划线或点。

    【讨论】:

    【解决方案3】:

    OrderedDict 字典类型支持破折号: https://docs.python.org/2/library/collections.html#ordereddict-objects

    这似乎是 OrderedDict 实施的副作用。请注意,键值对实际上是作为集合传入的。我敢打赌,OrderedDict 的实现不使用在集合中传递的“键”作为真正的 dict 键,从而解决了这个问题。

    由于这是 OrderedDict 实现的副作用,因此您可能不想依赖它。但它有效。

    from collections import OrderedDict
    
    my_dict = OrderedDict([
        ('has-dash', 'has dash value'), 
        ('no dash', 'no dash value') 
    ])
    
    print( 'has-dash: ' + my_dict['has-dash'] )
    print( 'no dash: ' + my_dict['no dash'] )
    

    结果:

    has-dash: has dash value
    no dash: no dash value
    

    【讨论】:

      猜你喜欢
      • 2021-04-10
      • 2019-09-01
      • 1970-01-01
      • 2013-11-13
      • 1970-01-01
      • 1970-01-01
      • 2019-06-15
      • 2021-10-17
      相关资源
      最近更新 更多