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

Time:05-02

I have the following in an HTML file:

{% for ctype in course.sections %}
    {% for instr in course.instructors[ctype] %}
        ...
        <a 
           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

CodePudding user response:

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
  }
)
  • Related