Skip to content
Advertisement

How to set a variable from inside a for loop that can be accessed from outside the for loop [Jinja]

When a user clicks a link, I want Jinja to set a variable called {{ contact_clicked }} that is equal to {{ contact }}.

I could do <a href="/?{% contact_clicked = contact %}">.....</a>. However, that variable is then inaccessible outside of the for loop.

I tried creating a list and then appending a variable to the list and then accessing the first variable in the list. However, the list doesn’t wipe when the page reloads (or at any other time) so the variable is set forever.

EDIT 1:
My for loop looks like this:

    {% set contact_clicked = "" %}

    {% for contact in contact_list %}
        {% if contact in fake_list %}
            <h4 style="color: rgb(200,100,100)"> {{ contact }} NO SUCH ACCOUNT </h4>
        {% else %}
            <a href="/?{% contact_clicked = contact %}"> <h4 style="color: rgb(200,200,200)"> {{ contact }} </h4> </a>
        {% endif %}
    {% endfor %}

I’m talking about a Jinja2 for loop, not a Python for loop.

Advertisement

Answer

SOLVED Read on to see how…
To set a variable, I told Jinja to direct me to /contact_msg/{{ contact }}. Let’s say I clicked on a contact called ‘bob’. I would be directed to /contact_msg/bob. The code is below

{% for contact in contact_list %}
    {% if contact in fake_list %}
        <h4 style="color: rgb(200,100,100)"> {{ contact }} NO SUCH ACCOUNT </h4>
    {% else %}
        <a href="/contact_msg/{{ contact }}"> <h4 style="color: rgb(200,200,200)"> {{ contact }} </h4> </a>
    {% endif %}
{% endfor %}

Then, in doing this the user is directed to

@app.route('contact_msg/<contact>')
def contact_msg_page( contact ):
    session['contact_clicked'] = contact
    return redirect( url_for( 'home' ) )

in Flask. Because contact is the argument in def contact_msg_page, a local variable in Python called contact is set to {{ contact }} (the link that the user clicked on). I then set a session variable called contact_clickedorsession['contact_clicked'] to be equal to the Python variablecontact. Now that I’ve done that, I can access the session variable contact_clicked and do all the things I wanna do with it (e.g. when the user clicks on a contact in their contact list, it selects them to have a message sent to them by the user who clicked on them) <– That’s a mouthful.

I hope that this helps anyone who is having a similar problem to me. If anyone wants to ask any questions, ask away. I’d love to help you.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement