大佬教程收集整理的这篇文章主要介绍了如何从Django模板中访问包含连字符的字典键?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
如果您不想重组对象,那么自定义模板标签可能是唯一的选择。对于使用任意字符串键访问字典,此问题的答案提供了一个很好的示例。
对于懒惰的人:
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" %}
您甚至可以为子属性提供某种字符串分隔符(例如’__’),但我将其留给作业:-)
以上是大佬教程为你收集整理的如何从Django模板中访问包含连字符的字典键?全部内容,希望文章能够帮你解决如何从Django模板中访问包含连字符的字典键?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。