Flask/Jinja: Is there a way to use a Jinja variable as a parameter name in a Python call?

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!
Flask/Jinja: Is there a way to use a Jinja variable as a parameter name in a Python call?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 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
  }
)


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x