S
S
Sergey Eremin2019-01-25 15:57:32
Django
Sergey Eremin, 2019-01-25 15:57:32

How to "convert types" and fix strange if work in Jinja?

Faced with the strangeness of the Jinja template engine in Django. You need to set selected for the rendered dropdown option . I do it like this:

<select name="ft">
    <option value="0">Все ({{ total_item }} шт.)</option>{% for i in menu_typ %}
    <option value="{{ i.id }}"{% if request.GET.ft == i.id %} selected{% endif %}>
        {{ i.szName|capfirst }} ({{ i.Num }} шт.)
    </option>{% endfor %}
</select>

No selected for any option appears.
, {% if request.GET.ft == i.id %}does not work in principle. All sorts of experiments have shown that the cause of the type mismatch is: i.id -- number; request.GET.ft -- string. It was possible to bring both variables to the same type using the crutch add -- {% if request.GET.ft|add:0 == i.id|add:0 %}. Thus, if you do this:
<select name="ft">
    <option value="0">Все ({{ total_item }} шт.)</option>{% for i in menu_typ %}
    <option value="{{ i.id }}"{% if request.GET.ft|add:0 == i.id %} selected{% endif %}>
        {{ i.szName|capfirst }} ({{ i.Num }} шт.)
    </option>{% endfor %}
</select>

Everything is working. Is it a crutch, or does everyone do it? What other options are there?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Animkim, 2019-01-25
@Animkim

It’s not easier in the same place as menu_typ, to process the whole thing and return a list of some kind like this:

[{'object': object, 'selected': 'selected'},  {...}, {...}]

# html
{% for item in menu_typ %}
   <option value="{{ item.object.id }}" {{ item.selected }}>
        {{ item.object.szName|capfirst }} ({{ item.object.Num }} шт.)
    </option>
{% endfor %}

или [(object, 'selected'),  {object, ''), (...)]

{% for item, selected in menu_typ %}
   <option value="{{ item.id }}" {{ selected  }}>
        {{ item.szName|capfirst }} ({{ item.Num }} шт.)
    </option>
{% endfor %}

R
Roman, 2019-02-25
@skipirich

I would add the variable ft = int(request.GET.ft) to the context in the view and compare them in the template {% if ft == i.id %}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question