user109606
user109606

Reputation: 51

I cant use a variable inside an if statement in jinja

I'm trying to use a parameter in an if statement and it isn't working. I also tried using {{ }}.

@module002.route('/forum/<course_id>', methods=['GET', 'POST'])
@login_required
def module002_forum(course_id):
    form = CommentForm()

    if request.method == 'GET':
        cursos = Follow.query.filter_by(user_id=current_user.id)
        texto = Comment.query.filter_by(course_id=course_id).all()
        id_mensaje = list(text.user_id for text in texto)
        usuarios = User.query.filter(User.id.in_(id_mensaje)).all()
        usuarios = {user.id: user for user in usuarios}
        return render_template("module002_forum.html", module='module002', course_id=course_id,
                           form=form, cursos=cursos, texto=texto, user=current_user, usuarios=usuarios,db=get_db())
    elif request.method == 'POST':
        if current_user.is_authenticated and form.validate_on_submit():
            comentario = Comment(user_id=current_user.id,course_id=course_id,comment=form.comment.data)
            db.session.add(comentario)
            db.session.commit()
            flash("Comment added")
        else:
            flash("Error añadiendo comentario")
        return redirect(url_for('module002.module002_forum', course_id=course_id))
{% extends 'base.html' %}
{% import "bootstrap/wtf.html" as wtf %}

{% block content %}

<nav class="navbar navbar-default">
    <div class="container-fluid">
        <div class="btn-group btn-group-justified">
            {% for i in cursos %}
            <a class={% if i.course_id==course_id %}"btn btn-primary"{%else%}"btn btn-primary active"{%endif%}
                href="{{ url_for('module002.module002_forum', course_id=i.course_id) }}">{{
                i.course_name }}</a>
            {% endfor %}
        </div>
    </div>
</nav>

Upvotes: 2

Views: 161

Answers (2)

IoaTzimas
IoaTzimas

Reputation: 10624

Add spaces between curly brackets and else/endif. It must be:

{% else %} and {% endif %}

instead of

{%else%} and {%endif%}

Upvotes: 1

Detlef
Detlef

Reputation: 8592

The following variant should meet your requirements.

<a 
   class="btn btn-primary {{ ('','active')[i.course_id==course_id] }}"
   href="{{ url_for('module002.module002_forum', course_id=i.course_id) }}"
>{{ i.course_name }}</a>

You should also specify the type of variable in the rule, so you can be sure that the comparison works.

@module002.route('/forum/<int:course_id>', methods=['GET', 'POST'])

Upvotes: 2

Related Questions