0

Hello I have an html file with code similar to this:

<div class="form-group">
              <div class="input-group input-group-alternative">
                <div class="input-group-prepend">
                  <span class="input-group-text"><i class="ni ni-key-25"></i></span>
                </div>
                {{ form.abc1(placeholder="abc 1",class="form-control",type="password")}}
              </div>
            </div>
            <div class="form-group">
              <div class="input-group input-group-alternative">
                <div class="input-group-prepend">
                  <span class="input-group-text"><i class="ni ni-time-alarm"></i></span>
                </div>
                {{ form.abc2(placeholder="abc 2",class="form-control") }}
              </div>
            </div>
            <div class="form-group">
              <div class="input-group input-group-alternative">
                <div class="input-group-prepend">
                  <span class="input-group-text"><i class="ni ni-time-alarm"></i></span>
                </div>
                {{ form.abc3(placeholder="abc 3",class="form-control") }}
              </div>
            </div>

How could I make it so with a jinja for loop I can do something like the following python's solution:

i = 1
while i < 3:
  exec(f"abc{i} = {i}")
  i += 1

basically I need to make abcs in the html code using a jinja loop

{% for element in abclist %}

and here be able to define the following:

{{ form.abc%element here%(placeholder="abc %element here%",class="form-control") }}
  • instead of `exec(f"abc{i} = {i}")` you can pass a list to jinja template while rensering, `exec(f"abc{i} = {i}")` seems a strange and overkill and not a good use for me. – Epsi95 Jul 10 '21 at 16:01
  • my problem is getting how to put a variable inside this block; {{ form.abc3(placeholder="abc 3",class="form-control") }} – kkkkkkkkkkkkkkkkk Jul 10 '21 at 16:04
  • the biggest mistake is using `exec(f"abc{i} = {i}")` to create unique variables. You should use standard list for this `abc = []`, `abc.append(i)` - and then you can use `for`-loop in Python and in Jinja to work with this. And all values (like `placeholder`) you should set in Python before you send it to Jinja – furas Jul 10 '21 at 20:08

1 Answers1

0

Since you cannot have nested double brackets in Jinja like this {{ {{}} }} The best (and cleaner) solution would be to use macros. Shown here

Then you can use your loop:

{% for element in form %}
{{ render_field(element) }}
mmi-coding
  • 18
  • 4