问题
Im trying to make a simple blog website with the Flask framework. Each entry in my blog has a title, text and comments. the title and text are stored in a table named entries and the comments in a table named comments that links the comments to the corresponding entry with a foreign key.
The problem I have now is that I want to display the comments in my html file. To do is I want to call a python function named show_comments in my html file while I'm in a for loop. The python function looks like this:
@app.route('/comments/<entryid>')
def show_comments(entryid):
db = get_db()
curId = db.execute('select id, comment from comments where entry_id=entryid order by id desc')
comments = [dict(id=row[0], comment=row[1]) for row in curId.fetchall()]
return render_template('show_entries.html', comments=comments)
My template looks like this:
% extends "layout.html" %}
{% block body %}
{% if session.logged_in %}
<form action="{{ url_for('add_entry') }}" method=post class=add-entry>
<dl>
<dt>Title:
<dd><input type=text size=30 name=title>
<dt>Text:
<dd><textarea name=text rows=5 cols=40></textarea>
<dd><input type=submit value=Share>
</dl>
</form>
{% endif %}
<ul class=entries>
{% for entry in entries %}
<li><h2>{{ entry.title }}</h2>{{ entry.text }}
{{ url_for('show_comments', entryid=entry.id) }}
<ul class=comments>
{% for acomment in comments %}
<li>{{ acomment.comment }}
</li>
</br>
</ul>
{% endfor %}
{% if session.logged_in %}
<form action="{{ url_for('add_comment', key=entry.id) }}" method=post class=add-entry>
<dl>
<dt>Comment:
<dd><textarea name=comment rows=2 cols=40></textarea>
<dd><input type=submit value=Comment>
</dl>
</form>
{% endif %}
{% else %}
<li><em>Unbelievable. No entries here so far</em>
{% endfor %}
</ul>
{% endblock %}
回答1:
You haven't really told us what your problem is so I don't know if this will help. But I'll point out three specific mistakes here:
The first is that you're putting your comments in an unordered list (the <ul>
tag) but you put the end tag (</ul>
) inside the loop instead of outside it.
</br>
should be written <br />
, but really that tag doesn't belong there in the first place.
Second, your HTML is broken. HTML attributes (the parts in tags like type=submit
) should have quotation marks around the values. For example, it should look like type="submit"
. Most browsers are forgiving when it comes to things like that, but it's better not to count on that and write correct HTML.
来源:https://stackoverflow.com/questions/13350091/looping-over-a-list-in-a-jinja2-template