skip to Main Content

Hi everyone I’m stucking on jinja and looking for the right way to loop my data on my front, someone can help me with that ?

my json data on mongodb

{
    "_id": {
        "$oid": "623492fea76c5404b9f57476"
    },
    "name": "pour ou contre ",
    "created_by": "admin",
    "created_at": {
        "$date": {
            "$numberLong": "1647612670472"
        }
    },
    "subject": "politique"
}

json data

I want to loop only room where subject == value like that

{% if current_user.is_authenticated %}
    {% for room in rooms %}
        {% if room.subject == 'politique' %}
            {{ room.room_name }
        {% endif %}
    {% endfor %}
{% endif %}

but jinja displaying all my room elements, I wanna just displaying room where subject == "politique"
I didn’t find the right way to do that !

can someone help me ?

2

Answers


  1. Chosen as BEST ANSWER

    i fixed this just bad call in render template thx for your help AKX


  2. There are some issues with your template, but I think those are typos. You’re not showing how you’re actually loading the rooms, and I think the issue is in that part.

    The code below works for me. Note that I load the rooms from a string, as you’re not showing how you load it.

    from jinja2 import Template
    import json
    
    
    json_string = """[
        {
            "_id": {
                "$oid": "623492fea76c5404b9f57476"
            },
            "name": "pour ou contre ",
            "created_by": "admin",
            "created_at": {
                "$date": {
                    "$numberLong": "1647612670472"
                }
            },
            "subject": "politique"
        },
        {
            "_id": {
                "$oid": "623492fea76c5404b9f57476"
            },
            "name": "no pour ou contre ",
            "created_by": "admin",
            "created_at": {
                "$date": {
                    "$numberLong": "1647612670472"
                }
            },
            "subject": "not_politique"
        }
    ]"""
    
    
    rooms = json.loads(json_string)
    tm = Template("""{% for room in rooms %}
        {% if room.subject == 'politique' %}
           {{ room.name }}
        {% endif %}
    {% endfor %}""")
    
    output = tm.render(rooms=rooms)
    print(output)
    

    output

           pour ou contre
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search