Jan
Jan

Reputation: 55

Django template html variable inside a variable

In my views i created a variable passing in the context that looks like this

{13: {112: 33.333333333333336, 120: 66.66666666666667, 125: 66.66666666666667}, 14: {110: 20.0, 111: 20.0, 113: 20.0, 121: 40.0, 126: 40.0}}

In my template i am inside a loop from questions, and want to assign this values to answers inside the question:

{% for question in questions %}
    <div class="ui basic padded segment left aligned">
        <h4 class="ui header">
            Question {{ forloop.counter }} / {{ questions|length }}: {{ question.prompt }}
        </h4>
        <ul>
            {% for option in question.answer_set.all %}
            <li> {{ forloop.counter }}) {{option.text}}: 
                 {{ ans.{{ question.pk }}.{{ option.pk }} }} %.
                
                {{ ans.13.120 }} 
            </li>
            {% endfor %}
        </ul>
    </div>
    {% endfor %}

If I use {{ ans.13.120 }} it works, but is not dynamic.... I want a way to use variables inside the {{ }}... something like: {{ ans.(question.pk).(option.pk) }}...

Is it possible?

Upvotes: 0

Views: 421

Answers (2)

Mohamed Beltagy
Mohamed Beltagy

Reputation: 623

if you want to do it in templates level you can make custom tag for it and passing the dictionary and the key then you will get the value

Upvotes: 1

wm3ndez
wm3ndez

Reputation: 723

You should do that work in the view. Avoid writing logic in templates.

Upvotes: 0

Related Questions