简体   繁体   中英

Python template forloop doesn't work more than one time

I am new to Python, I am using flask. I am trying to fetch the data from database, which I successfully get. The data is going to be used in multiple place like in different dropdown selects and values in option would be dynamic from database in same index template.

But when I run for loop only in template, only the first loop works other doesn't work at all. I have also check the data from database is retrieving. By first loop I mean lets suppose I iterate loop in select dropdown list like this:

Python code:

def configure_routes(app):
@app.route('/')  # URL '/' to be handled by main() route handler
def main(name=None):
ret = class.get_data()
return render_template('index.html', name=name, data=ret)

HTML markup:

<select id="targ_xyz" class="form-control">
<option>Select Target xyz</option>
<option>
{% for rows in data %}
{{rows}}
{% endfor %}
</option>

Now this code works, just next to it there is next select dropdown with the same loop and and the results from same data variable has to be extracted.

<select id="targ_tech" class="form-control">
<option>Select Target tech</option>
<option>
{% for row2 in data %}
{{row2.tech}}
{% endfor %}
</option>

This is my template where i want to add the python code in select options
<div id = "tech_sep">
<select id="sel_sep_tech" class="form-control">
<option>Select Target Technology</option>
</select>
</div>
<div id = "abc_ch">
<select id = "abc_ch_sel" class="form-control">
<option>Choose Expertise</option>
</select>   
</div>
</div>
<div class="form-group col-md-3">
<div id = "targ_sep">
<select id="xyz_ch" class="form-control">
<option>Select Target</option>
</select>
</div>

This code or below this any loop doesn't work at all. I would appreciate if someone can help, or someone can guide me how many loops we can use in one html template with Python also how to use them in proper way.

THanks.

I've done something similar in the past. you could test the following, as you stated that the for loop is based on the same variable?

{% for rows in data %}
  <select id="targ_xyz" class="form-control">
  <option>Select Target xyz</option>
  <option>
    {{rows}}
  </option>

  <select id="targ_tech" class="form-control">
  <option>Select Target tech</option>
  <option>
    {{rows.tech}}
  </option>
{% endfor %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM