Reputation: 4353
On Google app engine, I'd like to use two variables in a template for loop: I need to input, say, 10 items. If there are already some items in the datastore, then show them, otherwise, leave the field blank. How do I do it? Thanks.
BTW, I noticed that there is "multifor" in Django, but I don't know how to install it on GAE.
main.py:
def mainPage(webapp2.RequestHandler):
query = db.Query(Item)
items = query.fetch(limit=10)
template_values = {'range': range(10), 'items': items}
common.render(handler, 'main.html', template_values)
main.html:
<form action=... method="post">
{% for i in range; for item in items %}
<input type="text" name="name" value="item.name">
{% endfor %}
<input type="submit">
</form>
Upvotes: 2
Views: 738
Reputation: 16563
You may find these ideas helpful as well
(1) If the loop in your template is
{% for item in items %}
then you can use the variable {{forloop.counter0}}
or {{forloop.counter1}}
to get the index of the loop.
(2) You can pass a Python list of tuples to your template and write the for loop this way:
{% for index, name in names %}
Upvotes: 1
Reputation: 37259
Not sure which templating engine you are using, but what about creating a list of 10-elements and filling it with the results of your query? Something like:
my_list = [None for _ in range(10)]
Then, once you get your query results, add them to the list (the objects will be returned as a list of objects, so this is just a conceptual example):
>>> new_list = ['one', 'two', 'three']
>>> my_list[:len(new_list)] = new_list
>>> my_list
['one', 'two', 'three', None, None, None, None, None, None, None]
Now when you pass my_list
into the template:
<form action=... method="post">
{% for item in my_list %}
{% if item %}
<input type="text" name="name" value="item.name">
{% else %}
<input type="text" name="<your_blank_value>" value="<your_blank>">
{% endif %}
{% endfor %}
<input type="submit">
</form>
Upvotes: 5