ChocoBomb
ChocoBomb

Reputation: 301

Check if element from list is inside another list in django template

I'm making a for loop through a list. For each element in this list, I would like to know if this element could be egal to one of 4 words from another list.

This is my example in order to describe the situation:

From my view:

content = ['**Added**:\n', '* something (toto-544)\n', '\n', '**Changed**:\n', ...]

operations = ['Added', 'Changed', 'Fixed', 'INTERNAL']

From my HTML file:

{% for line in content %}
  {% if line in operations %}
    <tr class="table-subtitle">
      <td colspan="12">{{ line }}</td>
    </tr>
  {% else %}
    <tr class="table-value-content">
      <td colspan="12">{{ line }}</td>
    </tr>
  {% endif %}
{% endfor %}

It should display the first line element different than the second one (I changed color between both classes). Because line[0] is in operations and not line[1].

Do you have any idea why it doesn't work through my for loop/if statement ?

Upvotes: 2

Views: 864

Answers (2)

Ralf
Ralf

Reputation: 16505

This check is a bit complex for a template, but you can easily achieve it in Python code using the any() function. Since the strings are longer, you could check if the operations are in the string:

any(
    op.lower() in s.lower()
    for op in operations)

Test code:

content = ['**Added**:\n', '* something (toto-544)\n', '\n', '**Changed**:\n',]
operations = ['Added', 'Changed', 'Fixed', 'INTERNAL']

for s in content:
    print()
    print('s:', repr(s))
    print('s in operations:', s in operations)
    print('custom check:   ', any(op.lower() in s.lower() for op in operations))

The result is:

s: '**Added**:\n'
s in operations: False
custom check:    True

s: '* something (toto-544)\n'
s in operations: False
custom check:    False

s: '\n'
s in operations: False
custom check:    False

s: '**Changed**:\n'
s in operations: False
custom check:    True

Upvotes: 3

ChocoBomb
ChocoBomb

Reputation: 301

As said @shourav 'Added' and '**Added**:\n' is not the same thing. It was a mistake from me because I believed in worked like icontains.

Upvotes: 2

Related Questions