首页 > 解决方案 > html表中行的条件样式

问题描述

我有一个 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 %}

标签: htmlcsstr

解决方案


你能检查一下下面的代码是否可以工作。在您的 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>

推荐阅读