Home > Software engineering >  flask jinja2 variable of variable
flask jinja2 variable of variable

Time:11-16

I am trying to access a variable of a object in jinja2 using this code:

{% for row in rows.items %}
  <tr>
    {% for column in model_settings['table_columns'] %}
      <td>
        <p>{{ row.column }}</p>
      </td>
    {% endfor %}
  </tr>
{% endfor %}

what I want is if column was username I would want it to give me row.username. sorry for the bad explanation.

CodePudding user response:

Jinja2 has the builtin attr filter to access an attribute of an object. The name of the attribute can be a static string, or in your case: a string stored in a variable:

{% for row in rows.items %}
  <tr>
    {% for column in model_settings['table_columns'] %}
      <td>
        <p>{{ row|attr(column) }}</p>
      </td>
    {% endfor %}
  </tr>
{% endfor %}
  • Related