问题描述
我在html中有一个表,该表从PY中的SQL查询获取数据。我的sql表中的列之一是类型(tp)。我希望html表格为相同类型的每一行显示一种颜色,而为相反类型显示另一种颜色。这是一本财务日记,因此当您输入费用时,sql会保存该信息。我希望表格以红色显示历史记录和费用行,以绿色显示收入行。这是我的PY和HTML代码。请帮助我迷路
@app.route("/history")
@login_required
def history():
"""Show history of inputs"""
inputs = db.execute("""
SELECT amount,category,tp,transacted
FROM inputs
WHERE user_id = :user_id
ORDER BY transacted ASC
""",user_id=session["user_id"])
return render_template("history.html",inputs=inputs)
{% extends "layout.html" %}
{% block title %}
History
{% endblock %}
{% block main %}
<table class="table table-striped">
<thead>
<tr>
<th>Type</th>
<th>Amount</th>
<th>Category</th>
<th>Transacted</th>
</tr>
</thead>
<tbody>
{% for input in inputs %}
<tr>
<td>{{input["tp"]}}</td>
<td>{{input["amount"]}}</td>
<td>{{input["category"]}}</td>
<td>{{input["transacted"]}}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock %}
解决方法
可以检查以下代码是否有效。 在CSS文件中定义“红色”和“绿色” CSS类。
<tbody>
{% for input in inputs %}
<tr>
{% if input["tp"] == 'expense' %}
<td class="red">{{input["tp"]}}</td>
<td class="red">{{input["amount"]}}</td>
<td class="red">{{input["category"]}}</td>
<td class="red">{{input["transacted"]}}</td>
{% else %}
<td class="green">{{input["tp"]}}</td>
<td class="green">{{input["amount"]}}</td>
<td class="green">{{input["category"]}}</td>
<td class="green">{{input["transacted"]}}</td>
{% endif %}
</tr>
{% endfor %}
</tbody>