1

Is there a way in Jinja2 to construct a variable name and then call it? I want to do something like this:

{% for type in ('Students', 'Faculty', 'Groups') %}
    {% set import_name = 'latest_' + type|lower + '_import' %}
    {{ type }}: {{ import_name.created_at }}
{% endfor %}

I would expect the output to be something like this:

Students: 5/26/2016
Faculty: 5/25/2016
Groups: 5/25/2016

I have the variables latest_students_import, latest_faculty_import, and latest_groups_import set in the template scope, and would like to avoid having a large conditional in my for loop. I set import_name based on the type, and then try to "call" import_name. I want something like {{ call(import_name) }}. Is this possible, or is there another way I can go about this?

In this case, I suppose I could do it in reverse order loop through the three template variable names, and then "print" the shortened name, capitalized, but I would prefer to do it this way.

Dan
  • 147
  • 2
  • 8
  • 1
    why not put a dict or a list together on the server-side, which contains your variables? send that object to jinja as a template variable. it's easy that way. as it stands you are just setting import_name equal to string, which won't have the created_at attribute. – wgwz May 26 '16 at 21:46
  • Right, and loop through the constructed dict. That works; thanks! – Dan May 26 '16 at 21:53
  • no problem. i will move this to an answer, if it indeed solves your problem. – wgwz May 26 '16 at 22:10

1 Answers1

1

One possibility is to create a dict or a list on the server-side which contains your variables. You can then send that object to Jinja as a template variable. As it stands you are just setting import_name equal to string, which won't have the .created_at attribute.

wgwz
  • 2,642
  • 2
  • 23
  • 35