You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Datatables自定义排序实现及自动更新好友排行榜配置技术求助

Alright, let’s walk through building your auto-updating friend leaderboard with custom sorting step by step—covering everything from data scraping to Datatables tweaks that make your leaderboard both functional and user-friendly.

Step 1: Data Collection & Auto-Update (Scraper + Cronjob)

First, we’ll build a scraper to pull friend data, merge columns for better sorting logic, and output to a CSV. Then set up a cronjob to automate updates.

Scraper Script (Python Example)

We’ll calculate a Net_Wins column (Wins - Losses) as our merged sorting metric—this is way more practical than sorting by Wins or Losses alone.

import csv
from datetime import datetime

# Replace this with your actual scraping logic to fetch friend data
friends_data = [
    {"Name": "Alice", "Rank": "S", "Wins": 25, "Losses": 5},
    {"Name": "Bob", "Rank": "A", "Wins": 20, "Losses": 8},
    {"Name": "Charlie", "Rank": "S", "Wins": 18, "Losses": 3},
    {"Name": "Dave", "Rank": "B", "Wins": 15, "Losses": 10},
]

# Merge Wins/Losses into a practical sorting column
for entry in friends_data:
    entry["Net_Wins"] = entry["Wins"] - entry["Losses"]

# Write to CSV (this will be used by csv-to-html-table)
with open("leaderboard.csv", "w", newline="") as f:
    fieldnames = ["Name", "Rank", "Wins", "Losses", "Net_Wins"]
    writer = csv.DictWriter(f, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerows(friends_data)

Set Up Cronjob for Auto-Updates

  1. Open your crontab editor: crontab -e
  2. Add a line to run the scraper on a schedule (e.g., daily at midnight):
    0 0 * * * /usr/bin/python3 /path/to/your/scraper.py
    
  3. Save and exit—Cron will automatically handle the scheduled updates.
Step 2: Generate Base HTML Table with csv-to-html-table
  1. Place your leaderboard.csv in the project’s data directory.
  2. Update the project’s config.json to point to your CSV file (change table.csv to leaderboard.csv) and ensure enable_datatables is set to true.
  3. Run the project (per its docs) to generate the initial HTML table.
Step 3: Implement Custom Datatables Sorting

This is where we tackle your specific sorting requirements: custom Rank order and optimized Wins/Losses sorting.

Custom Rank Sorting

If your Rank uses a non-alphabetical priority (e.g., S > A > B > C), we need a custom sorting plugin to tell Datatables how to order these values:

// Define weight for each Rank (adjust based on your actual rank system)
jQuery.extend(jQuery.fn.dataTableExt.oSort, {
    "rank-pre": function(a) {
        const rankWeight = {"S": 4, "A": 3, "B": 2, "C": 1, "D": 0};
        return rankWeight[a] || -1; // Unknown ranks go to the bottom
    },
    "rank-asc": function(a, b) {
        return a < b ? -1 : a > b ? 1 : 0;
    },
    "rank-desc": function(a, b) {
        return a < b ? 1 : a > b ? -1 : 0;
    }
});

Optimized Wins/Losses Sorting

We’ll use the hidden Net_Wins column to power sorting for both Wins and Losses columns, making the leaderboard more intuitive:

<script>
$(document).ready(function() {
    $('#table_id').DataTable({
        "columnDefs": [
            // Hide the Net_Wins column (it's only for sorting)
            { "targets": 4, "visible": false },
            // Assign custom rank sorting to the Rank column (index 1)
            { "targets": 1, "type": "rank" },
            // Make Wins/Losses columns sort by Net_Wins when clicked
            { "targets": 2, "orderData": [4] },
            { "targets": 3, "orderData": [4] }
        ],
        // Default sort: Rank (descending) first, then Net_Wins (descending)
        "order": [[1, "desc"], [4, "desc"]],
        // Optional: Tweak UI settings to fit your needs
        "paging": false,
        "searching": true,
        "info": false
    });
});
</script>
Final Checks
  • Test your cronjob by manually running the scraper to ensure the CSV updates correctly.
  • Adjust the rankWeight object in the JavaScript if your Rank system changes.
  • Tweak Datatables settings (like pagination or search) to match your desired user experience.

内容的提问来源于stack exchange,提问作者Darohitten

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 08:16:08