Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

210
Views
conditionally change django template variable

tl;dr

I need a template variable to change by concatenating strings along the way.

my issue

I'm looping through a queryset in my template, and inside the loop I'm checking if certain fields on the object match the current user. If so, then my variable changes and is finally applied as a class to an element.

{% for item in items %}
    {% with class="" %}
        {% if request.user == item.field1 %}
            /* append to class variable, ex: class=" field1" */
        {% endif %}
        {% if request.user == item.field2 %}
            /* append to class variable, ex: class=" field1 field2" */
        {% endif %}

        <div class="{{class}}"></div>
    {% endwith %}
{% endfor %}

So, if my request.user equals both item.field1 and item.field2 then my element would look like this:

<div class=" field1 field2"></div>

And if my request.user equals only item.field2 then my element would look like this:

<div class=" field2"></div>
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You can't do that in Django template language. You could potentially write a tag, but I don't see why you would want to; you can just do the whole thing inline.

<div class="{% if request.user == item.field1 %}field1{% endif %} {% if request.user == item.field2 %}field2{% endif %}"></div>
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!