在 HTML table - Django 项目中以相同颜色更改具有相同单元格值的行

Change the rows with the same cell value in the same color in HTML table - Django project

我在我的html文件中为我的Django项目创建了一个table,原始数据基于以下列表(这是一个很长的列表,所以我只列出了几行):

mylist=
[{'StartDate': '2021-10-02', 'ID': 11773, 'Receiver': Mike, 'Days':66 },
{'StartDate': '2021-10-03', 'ID': 15673, 'Receiver': Jane, 'Days':65}, 
... 
{'StartDate': '2021-10-5', 'ID': 34653, 'Receiver': Jack, 'Days':63}]

我的 Html 文件:

  <table class="table table-striped" id="dataTable" width="100%" cellspacing="0">
                                    
     <thead>
        <tr>
            <th>StartDate</th>
            <th>ID</th>
            <th>Name</th>
            <th>Days</th>
        
     </thead>
     <body>

{% for element in mylist %}

      <tr>
        <td>{{ element.StartDate}}</td>
        <td>{{ element.ID }}</td>
        <td>{{ element.Receiver }}</td>
        <td>{{ element.Days }}</td>

       </tr>
      {% endfor %}      
       </tbody>
                         
      </table>

我想使具有相同 ID 值的所有行都具有相同的颜色。请指教我应该在 <td>{{ element.ID }}</td> 中添加什么。谢谢!

我的部分 views.py:

client = gspread.service_account_from_dict(creds)


def CreateSheet(Return_record):
    sheet = client.open(Return_record).sheet1
    return sheet

from sheet2api import Sheet2APIClient


sheet = client.open('Return Record 2022')
sheet_instance = sheet.get_worksheet(0)
mylist = sheet_instance.get_all_records()
mylist


def table2022(request):
    return render(request,'table2022.html',{'mylist':mylist})

我们想要作为上下文传递的所有内容,我们应该保留在我们想要使用它的内部view。当我们有越来越多的代码时,它更具可读性。

我们要做的是为数字 0-9 定义一种颜色。我暂时选择一些灯colors,你可以随意更改它们。

views.py:

def table2022(request):
    mylist = sheet_instance.get_all_records()
    colors = {'0': 'aqua', '1': 'beige', '2': 'burlywood', '3': 'lightgrey', '4': 'silver', '5': 'skyblue', '6': 'lightblue', '7': 'lightpink', '8': 'lightgreen', '9': 'lawngreen'}
    context = {'mylist': mylist, 'colors': colors}

    return render(request, 'table2022.html', context)

现在,因为在模板中使用起来并不那么简单 Python,我们需要创建自定义 Template Tag。让我们从在您的应用程序中创建文件夹开始,我们将其命名为 custom_tags.py。它应该在 YourProject/your_app/templatetags/ 文件夹中创建,因此我们还必须在其中创建 templatetags 文件夹。

custom_tags.py:

from django import template

register = template.Library()

@register.filter(name='get_color')
def get_color(colors, number):
    return colors[str(number)[-1]]

your_template.html:

{% load custom_tags %}

...

{% for element in mylist %}
    <tr>
        <td>{{ element.StartDate }}</td>
        <td style="background-color: {{ colors|get_color:element.ID }}">
            {{ element.ID }}
        </td>
        <td>{{ element.Receiver }}</td>
        <td>{{ element.Days }}</td>
    </tr>
{% endfor %}

get_color 标签基本上是取整个 ID,然后只提取最后一个数字并将其变成一个字符串。之后它使用单个数字作为 colors 字典中的键并将相应的值传递给模板,它将成为有效的 html 颜色。

自定义标签用于 'implement' 一些 Pythonic 代码直接进入模板。不要过多使用它,因为大部分编码应该在 views.pymodels.py 等标准文件中。但有时也没有更好的办法。 :)

有关 Tags 的更多详细信息,请检查 Django's DOCS