如何从Django模板中访问包含连字符的字典键? [英] How do I access dictionary keys that contain hyphens from within a Django template?

查看:534
本文介绍了如何从Django模板中访问包含连字符的字典键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

We have a system built on a custom database, where many of the attributes are named containing hyphens, ie:

user-name
phone-number

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

These properties cannot be accessed in templates as follows:

{{ user-name }}

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

Django throws an exception for this. I'd like to avoid having to convert all of the keys (and sub-table keys) to use underscores just to work around this. Is there an easier way?

推荐答案

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

A custom template tag is probably the only way to go here if you don't want to restructure your objects. For accessing dictionaries with an arbitrary string key, the answer to this question provides a good example.

对于懒惰:

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, '')

你使用的就是这样: / p>

Which you use like so:

{% dictKeyLookup your_dict_passed_into_context "phone-number" %}

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

If you want to access an object's attribute with an arbitrary string name, you could use the following:

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)

p>

Which you would use like:

{% attributeLookup your_object_passed_into_context "phone-number" %}

您甚至可以提出某些字符串分隔符(如__)用于子属性,但是我将离开作业: - )

You could even come up with some sort of string seperator (like '__') for subattributes, but I'll leave that for homework :-)

这篇关于如何从Django模板中访问包含连字符的字典键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆