Accessing dict elements with leading underscores in Django Templates

前端 未结 2 2135
北荒
北荒 2020-12-10 15:52

I am trying to access elements of a dict with keys that start with the underscore character. For example:

my_dict = {\"_source\": \'xyz\'}

I\'m

2条回答
  •  遥遥无期
    2020-12-10 16:26

    The docs mention that you can't have a variable start with an underscore:

    Variable names must consist of any letter (A-Z), any digit (0-9), an underscore (but they must not start with an underscore) or a dot.

    but you can easily write a custom template filter to mimic the dictionary's get method:

    @register.filter(name='get')
    def get(d, k):
        return d.get(k, None)
    

    and

    {{ my_dict|get:"_my_key" }}
    

提交回复
热议问题