Home > front end >  accessing context variables that contain spaces
accessing context variables that contain spaces

Time:11-19

I have python dictionary, and I am passing its values to a html page to display them. i am able to access the values of the dictionary by using {{ value.xxx }} where the xxx is the element of the dictionary. the values appear on the screen no problem for name, age & height below. However the skill set component doesn't appear because of the space in the text. How can i set it so that i can access the elements that contain a space, like the skillset value below.

I have tried adding an underscore such as {{ value.skill_set }} but that doesn't seem to work.

Dictionary:

dict = {1: {'name': 'John', 'age': '27', 'height': '160', 'skill set': 'running'},
          2: {'name': 'Marie', 'age': '22', 'height': '170', 'skill set': 'swimming'}}

Html:

<table class="u-full-width" id="table2">
<thead >
    <tr>

    </tr>
  </thead>
 <tbody>
    {% for key,value in dict_items.items %}
    <tr>
        <th scope="row" style="text-align:center">{{ key }}</th>
        <td style="text-align:center">{{ value.name }}</td>
        <td style="text-align:center">{{ value.age }}</td>
        <td style="text-align:center">{{ value.height }}</td>
        <td style="text-align:center">{{ value.skill set }}</td>
    </tr>
    {% endfor %}
</tbody>
</table>

CodePudding user response:

<table class="u-full-width" id="table2">
<thead >
    <tr>

    </tr>
  </thead>
 <tbody>
    {% for key,value in dict_items.items %}
    <tr>
        <th scope="row" style="text-align:center">{{ key }}</th>

         {% for key_,value_ in value.items %}

        <td style="text-align:center">{{ value_ }}</td>

         {% endfor %}

    </tr>
    {% endfor %}
</tbody>
</table>

CodePudding user response:

Django templates use dot notation and there is no straight forward way to look up a key with a space in it. Your question has been asked before, and some solutions like using custom filters and template tags can be viewed here: Django templates: value of dictionary key with a space in it

  • Related