smsgrafica
smsgrafica

Reputation: 111

How to include random list element in a template

I have a variable questionchoice = ['one', 'two', 'three'] and want a random element of it to be included in a template.

I tried {% include 'questions/question-'{{ questionchoice|random }}'.html' %} but it doesn't work.

Any help, please?

EDIT:

I modified my variable to include the whole link:

questionchoice = ['questions/question-one.html', 'questions/question-two.html', 'questions/question-three.html']

After that I used this in my template:

{% with questionchoice|random as question %}
    {% include question %}
{% endwith %}

Upvotes: 0

Views: 134

Answers (1)

schillingt
schillingt

Reputation: 13731

You can't use a template filter for that argument with the include template tag. You can move that logic into your view method:

views.py

import random
def view(request):
    return render(request, {
        "question_template": "questions/question-{}.html".format(random.randint(1,3)),
    })

template

{% include question_template %}

Upvotes: 2

Related Questions