Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing dictionary by key in Django template

I'm passing a dictionary from my view to a template. So {"key1":"value1","key2":"value2"} is passed in and looping through key,value pairs is fine, however I've not found an elegant solution from access directly in the view from a specific key, say "key1" for example bu json.items["key1"]. I could use some if/then statements, but I'd rather do directly is there a way?

Here is looping code in the html template:

{% for key, value in json.items %}    <li>{{key}} - {{value}}</li>  {% endfor %} 
like image 357
disruptive Avatar asked Nov 02 '13 18:11

disruptive


People also ask

How do you grab a value from a dictionary?

You can use the get() method of the dictionary ( dict ) to get any default value without an error if the key does not exist. Specify the key as the first argument. The corresponding value is returned if the key exists, and None is returned if the key does not exist.

What does {% mean in Django?

{% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.

What are templates in Django?

A Django template is a text document or a Python string marked-up using the Django template language. Some constructs are recognized and interpreted by the template engine. The main ones are variables and tags. A template is rendered with a context.


1 Answers

The Django template language supports looking up dictionary keys as follows:

{{ json.key1 }} 

See the template docs on variables and lookups.

The template language does not provide a way to display json[key], where key is a variable. You can write a template filter to do this, as suggested in the answers to this Stack Overflow question.

like image 98
Alasdair Avatar answered Oct 02 '22 15:10

Alasdair