Access a variable in Django's template having its name in string

1
{% for x in array%}
   {% for y in x %}
      <h1>{{y}}</h1>
   {% endfor %}
{% endfor %}

With x in the second for the key of a dictionary whose value is an array, and x in the first for a string whose value is the x of the second for

How could it be done to take the value of the second x having its name as a string?

    
asked by G3l0 03.05.2017 в 10:09
source

1 answer

4

I recommend you do a custom filter Create a module in your app that is called templatetags and inside a file for your custom filters and labels, as indicated in the documentation.

In your filter file add this code:

@register.filter(name='clave')
def clave(dicc, key):
    try: return dicc[key]
    except KeyError: return 0

The filter acts on your dictionary and clave is the key. Since you do not provide a minimum, complete and verifiable example I'll give you a generic example.

{% for nombre in nombres %}
   Diccionario: {{ dicc | clave: nombre }}
{% endfor %}

Like any filter in Django, you can nest them and use it with other filters, for example, I use it like this:

{{pivot|clave:t|clave:'mini'|money}}

To convert this:

{'ejer': Decimal('152675.00'),
 'label': 'January de 2014',
 'mini': Decimal('159793.56'),
 'porc': '95.55',
 'rein': Decimal('0.00'),
 'sald': Decimal('7118.56')}

on something like this:

    
answered by 10.05.2017 / 22:21
source