1

I have the following in an HTML file:

{% for ctype in course.sections %}
    {% for instr in course.instructors[ctype] %}
        ...
        <a class="dropdown-item"
           href="{{ url_for(
                            'views.get_results',
                            user=current_user,
                            user_query=userQuery,
                            ctype=instr
                           ) }}">
        {{ instr }}
        </a>
        ...

where I am populating a dropdown menus in various parts of the page (see image), and would like to use ctype (as set in the outer loop) as the parameter name (e.g., REC=Aghli,+Sina). Essentially, I am trying to find the syntactically correct equivalent of

url_for('views.get_results',
        user=current_user,
        user_query=userQuery,
        {{ctype}}=instr
        )

Note that instr seems to be pulling its value from the for-loop already, so I'm not sure how to tell Jinja that I want to use a templated variable as the parameter name as well. Currently, I am getting a url like ...ctype=Ashli,+Sina... (just passing the parameter named ctype verbatim). Thank you for any help - please let me know if I can clarify anything! enter image description here

Collin Sinclair
  • 453
  • 1
  • 3
  • 12
  • if i understood correctly, you can use in the url_for arguments: `course_type=ctype, instructor=instr`, i.e. fixed variable names and depending on the `course_type`'s value, the `get_results` will do the appropriate processing. – ilias-sp Apr 29 '22 at 21:24
  • you should send `ctype` as value, not variable's name. – furas Apr 29 '22 at 21:39
  • 1
    Thank you for the suggestions - I see that this is probably the better approach, however, I am still curious if one can dynamically name a field through Jinja – Collin Sinclair Apr 29 '22 at 23:26

1 Answers1

1

As this all boils down to "Is it possible to pass a keyword argument where the keyword is a variable to a function in Python?", the answer is basically the same: yes, using a dictionary and passing it with **dict.

So in your case, you could do:

url_for(
  'views.get_results',
  **{
    'user': current_user,
    'user_query': userQuery,
    ctype: instr
  }
)
β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83