'Jinja2 template evaluate variable as attribute
I have a Jinja2 Template I'm working on for a database editing app, and I'm trying to make it 'extendible' - rather than hard-coding the editing page, I'm passing a list of attributes that I want in the table, and using a for loop to iterate over them. It works aside from one thing - in the hardcoded version, I use an attribute of an object that's being passed to see if that value has been set (they are all boolean), but I can't see how to get jinja2 to take the 'capability' and use that as an attribute of the 'pupil' object; i would have used 'eval' in Python, but can't see how to get this to work. Here's an idea of the code:
{% for capability in capability_list %}
<tr>
<td>{{ capability }}</td>
<td>
{% if pupil.capability %}
<img src="{{request.static_url('gdpr_permissions:static/tick.png')}}" width="25">
{% else %}
<img src="{{request.static_url('gdpr_permissions:static/cross.png')}}" width="25">
{% endif %}
</td>
<td>
<div class="onoffswitch">
<input type="checkbox" name="{{ capability }}" class="onoffswitch-checkbox" value ='No' id="{{ capability }}" checked>
<label class="onoffswitch-label" for="{{ capability }}">
<span class="onoffswitch-inner"></span>
<span class="onoffswitch-switch"></span>
</label>
</div>
</td>
</tr>
{% endfor %}
It's the {% if pupil.capability %}
part that doesn't work - I want this to become (say) pupil.web_access
and pupil.database_access
etc., following the capability list which is being iterated over.
Any ideas on how to get this working with jinja2, or how else it can be approached? The other idea I had was to iterate over the current settings in the python backend and then pass a list of booleans separately, but this seems to be adding an extra level of complexity.
Solution 1:[1]
This is because you are passing in a string instead of an attribute. Use getattr()
instead. Do something like getattr(pupil, capability)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Esir Kings |