1
1
from mkdocs import plugins
2
2
3
+ from bs4 import BeautifulSoup
4
+
3
5
4
6
# https://www.mkdocs.org/dev-guide/plugins/#events
5
7
8
+ colors = {
9
+ "简单" : "#46c6c2" ,
10
+ "中等" : "#fac31d" ,
11
+ "困难" : "#f8615c" ,
12
+ "Easy" : "#46c6c2" ,
13
+ "Medium" : "#fac31d" ,
14
+ "Hard" : "#f8615c" ,
15
+ }
16
+
6
17
7
18
@plugins .event_priority (90 )
8
19
def on_post_page (output , page , config ):
9
- difficulty = page .meta .get ('difficulty' )
10
- rating = page .meta .get ('rating' )
11
-
12
- # 在 h1 标题之后插入难度和评分信息及其样式
20
+ is_cn_problem_page = (page .edit_url or "" ).endswith ("README.md" )
21
+ difficulty = page .meta .get ("difficulty" )
22
+ rating = page .meta .get ("rating" )
23
+ if not difficulty and not rating :
24
+ return output
25
+ if rating :
26
+ rating = f"难度分 { rating } " if is_cn_problem_page else f"Rating { rating } "
13
27
html = str (output )
14
- # if difficulty:
15
- # # 找到 h1 标签的结束位置
16
- # h1_end = html.find('</h1>') + 5
17
- # # 在 h1 标签之后插入难度信息
18
- # html = html[:h1_end] + f'<p>Difficulty: {difficulty}</p>' + html[h1_end:]
19
- # if rating:
20
- # # 找到 h1 标签的结束位置
21
- # h1_end = html.find('</h1>') + 5
22
- # # 在 h1 标签之后插入评分信息
23
- # html = html[:h1_end] + f'<p>Rating: {rating}</p>' + html[h1_end:]
24
- return html
28
+ soup = BeautifulSoup (html , "html.parser" )
29
+ div = soup .new_tag ("div" , attrs = {"class" : "rating" })
30
+ soup .select_one ("h1" ).insert_after (div )
31
+ color = colors .get (difficulty ) or "black"
32
+ for s in (difficulty , rating ):
33
+ if not s :
34
+ continue
35
+ sub = soup .new_tag ("div" , attrs = {"class" : "rating-item" })
36
+ sub .string = str (s )
37
+ sub ["style" ] = f"color: { color } ;"
38
+ div .append (sub )
39
+ return str (soup )
0 commit comments