How to break for loop in jinja2 | Python – Django

Question:

Hi everyone please suggest me how to break for loop in jinja 2

I am using for loop with if condition and I want to break the loop if my if condition is true

this is my code

function refercheck(){
        var input_value = document.getElementById('refer').value;
        {% for i in refer %}
        document.getElementById("valid").innerHTML = '';
        if( input_value == "{{i.refercode}}" ){
            $('#valid').append('Referred By {{i.username}}');
        }

I am using this function in input onkeyup="refercheck()" and I an sending the dict from view function. My dict key is refer I am sending all user data and checking the input is same as other user refercode. The above code is give me only last row refercode is same please tell me how can I break for loop when my if condition is true or any other suggestions for it.

Asked By: Hemant Prajapat

||

Answers:

According to this answer, you can add the condition within the for loop statement

Simply:

function refercheck(){
    var input_value = document.getElementById('refer').value;
    document.getElementById("valid").innerHTML = '';
    {% for i in refer if input_value == i.refercode %}
        $('#valid').append('Referred By {{i.username}}');
    {% endfor %}


Update: Jinja2 does not support break or continue statments

you have to use other ways to solve this problem

here is what came to my mind
I didn’t try the code but here is the idea.

function refercheck(){
    var input_value = document.getElementById('refer').value;
    refer = {{refer|safe}}

    for (i = 0; i < refer.length; i++) {
        document.getElementById("valid").innerHTML = '';
        if( input_value == i.refercode ){
            $('#valid').append('Referred By '+i.username);
            break;
        }
    }
}

if i.refercode and i.refercode does not work try i['refercode'] and i['refercode']

Answered By: Shaheed Alhelal

Loop Controls
Import name: jinja2.ext.loopcontrols

This extension adds support for break and continue in loops. After enabling, Jinja provides those two keywords which work exactly like in Python.

Offers the ability to break and continue in template loops, just like the standard break and continue Python keywords.

source: https://jinja.palletsprojects.com/en/2.11.x/extensions/#loop-controls

Adding Extensions are added to the Jinja environment at creation time. Once the environment is created additional extensions cannot be added. To add an extension pass a list of extension classes or import paths to the extensions parameter of the Environment constructor. The following example creates a Jinja environment with the i18n extension loaded:

jinja_env = Environment(extensions=[‘jinja2.ext.loopcontrols’])

from django.templatetags.static import static
from django.urls import reverse
from jinja2 import Environment


def environment(**options):
    env = Environment(**options, extensions=['jinja2.ext.loopcontrols'])
    env.globals.update({
        'static': static,
        'url': reverse,
    })
    return env
Answered By: Nasir Usman

Jinja2 supports both break and continue. You just need to install ext.loopcontrols and activate jinja environment.

Here’s the doc link:
https://jinja.palletsprojects.com/en/2.11.x/api/?highlight=ext%20loopcontrols.

I’m not sure how this would work in Django, but in Flask you simply add the extension in the app factory:

    app = Flask(__name__,
                static_url_path='',
                static_folder='../app/static',
                template_folder='../app/templates')
    app.jinja_env.add_extension('jinja2.ext.loopcontrols')
Answered By: grommit
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.