Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
474 views
in Technique[技术] by (71.8m points)

python - Accessing dict elements with leading underscores in Django Templates

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 trying to access them in a Django template. Obviously I realise that you can't access underscored python variables from a Django template (because they are considered private in Python) but this is a dict object where any immutable object is a valid key.

I can't access the above dict in a Django template using {{ my_dict._source }} so I assume Django is preventing it. Is that accurate?

I am kind of hoping Django does something sane with variables that start with underscore like still doing dict lookups (the first thing is supposedly tries) but refuses to do attribute lookups, method calls and list index lookups since an underscored prefixed variable would be invalid. I am quickly loosing hope though.

For the record, I know someone will suggest to just change the dict but this is actually a multi-levelled dictionary returned by the rawes library when executing REST API request on a ElasticSearch instance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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" }}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...