WordPress 主题长代码块测试:三种语言
本文包含 Python、JavaScript 和 CSS 三个长代码块。代码围栏只使用标准语言标记,不添加插件专用的行号或高亮参数,方便观察主题本身的处理效果。
每个代码块均超过 70 行非空内容,包含中文注释、空行、缩进和超长行。行号、复制按钮、语法高亮及滚动方式由实际主题或插件决定。
Python:109 行
共 109 行,其中 97 行非空代码。下面的整个代码块用于测试长内容显示。
from dataclasses import dataclass
from decimal import Decimal
from typing import Iterable
import json
# 中文注释:使用内存数据演示订单计算,不需要安装第三方库。
@dataclass(frozen=True)
class Product:
sku: str
name: str
price: Decimal
category: str
stock: int
@dataclass(frozen=True)
class CartItem:
product: Product
quantity: int
@property
def subtotal(self) -> Decimal:
return self.product.price * self.quantity
class ShoppingCart:
def __init__(self) -> None:
self.items: list[CartItem] = []
self.discount_rate = Decimal("0.00")
self.shipping_fee = Decimal("8.00")
def add(self, product: Product, quantity: int = 1) -> None:
if quantity <= 0:
raise ValueError("数量必须大于零")
existing = next(
(item for item in self.items if item.product.sku == product.sku),
None,
)
total_quantity = quantity + (existing.quantity if existing else 0)
if total_quantity > product.stock:
raise ValueError(f"{product.name} 库存不足")
if existing is not None:
self.items.remove(existing)
self.items.append(CartItem(product, total_quantity))
def set_discount(self, rate: str) -> None:
value = Decimal(rate)
if not Decimal("0") <= value <= Decimal("1"):
raise ValueError("折扣比例应在 0 到 1 之间")
self.discount_rate = value
def calculate(self) -> dict[str, Decimal]:
subtotal = sum(
(item.subtotal for item in self.items),
start=Decimal("0.00"),
)
discount = (subtotal * self.discount_rate).quantize(Decimal("0.01"))
shipping = Decimal("0.00") if subtotal >= 100 else self.shipping_fee
if not self.items:
shipping = Decimal("0.00")
total = subtotal - discount + shipping
return {
"subtotal": subtotal,
"discount": discount,
"shipping": shipping,
"total": total,
}
def receipt(self) -> str:
amounts = self.calculate()
lines = ["订单明细", "=" * 48]
for item in self.items:
lines.append(
f"{item.product.name} × {item.quantity} = ¥{item.subtotal:.2f}"
)
lines.extend([
"-" * 48,
f"商品金额:¥{amounts['subtotal']:.2f}",
f"优惠金额:¥{amounts['discount']:.2f}",
f"配送费用:¥{amounts['shipping']:.2f}",
f"实际支付:¥{amounts['total']:.2f}",
])
return "\n".join(lines)
def build_catalog() -> list[Product]:
return [
Product("BOOK-001", "横线笔记本", Decimal("18.50"), "文具", 20),
Product("PEN-002", "黑色钢笔", Decimal("36.00"), "文具", 12),
Product("BAG-003", "帆布手提袋", Decimal("29.90"), "配件", 8),
Product("CUP-004", "白色马克杯", Decimal("42.00"), "生活", 10),
]
def filter_products(products: Iterable[Product], category: str) -> list[Product]:
return [product for product in products if product.category == category]
def main() -> None:
catalog = build_catalog()
cart = ShoppingCart()
cart.add(catalog[0], quantity=2)
cart.add(catalog[1], quantity=1)
cart.add(catalog[2], quantity=1)
cart.set_discount("0.10")
print(cart.receipt())
print("文具数量:", len(filter_products(catalog, "文具")))
# 超长行:用于检查代码区域横向滚动,下面是一行完整的字符串。
preview_url = "https://example.com/wordpress/theme/code-block/preview?language=python&test=horizontal-scroll&article=long-code-block&preserve_indentation=true&show_line_numbers=true&theme=dark&message=中文与English混合内容"
print("预览地址:", preview_url)
print(json.dumps({key: str(value) for key, value in cart.calculate().items()}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
这是 Python 代码块结束后的正文。检查它是否正常显示,以及代码块与正文之间的间距。
JavaScript:117 行
共 117 行,其中 104 行非空代码。下面的整个代码块用于测试长内容显示。
"use strict";
// 中文注释:使用纯 JavaScript 处理示例文章,不依赖网络请求。
const articles = [
{ id: 101, title: "Markdown 基础", category: "写作", views: 328, published: true },
{ id: 102, title: "代码块样式检查", category: "主题", views: 215, published: true },
{ id: 103, title: "Obsidian 发布笔记", category: "写作", views: 486, published: false },
{ id: 104, title: "WordPress 排版", category: "主题", views: 592, published: true },
{ id: 105, title: "移动端阅读体验", category: "设计", views: 173, published: true },
{ id: 106, title: "长代码滚动测试", category: "设计", views: 284, published: false },
];
class ArticleRepository {
constructor(records = []) {
this.records = records.map((record) => ({ ...record }));
}
findById(id) {
return this.records.find((record) => record.id === id) ?? null;
}
getPublished() {
return this.records.filter((record) => record.published);
}
getByCategory(category) {
return this.records.filter((record) => record.category === category);
}
update(id, changes) {
const index = this.records.findIndex((record) => record.id === id);
if (index === -1) {
throw new Error(`没有找到文章:${id}`);
}
this.records[index] = {
...this.records[index],
...changes,
id,
};
return { ...this.records[index] };
}
getStatistics() {
const totalViews = this.records.reduce((sum, item) => sum + item.views, 0);
const publishedCount = this.getPublished().length;
return {
total: this.records.length,
published: publishedCount,
drafts: this.records.length - publishedCount,
views: totalViews,
averageViews: this.records.length ? Math.round(totalViews / this.records.length) : 0,
};
}
}
function groupByCategory(records) {
return records.reduce((groups, record) => {
const key = record.category;
if (!groups[key]) {
groups[key] = [];
}
groups[key].push({ ...record });
return groups;
}, {});
}
function escapeHtml(value) {
const entities = {
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'",
};
return String(value).replace(/[&<>"']/g, (character) => entities[character]);
}
function renderArticleCard(article) {
const title = escapeHtml(article.title);
const category = escapeHtml(article.category);
return [
'<article class="article-card">',
` <span class="article-card__category">${category}</span>`,
` <h2 class="article-card__title">${title}</h2>`,
` <p class="article-card__meta">阅读量:${article.views}</p>`,
"</article>",
].join("\n");
}
async function createReport(repository) {
const statistics = repository.getStatistics();
const published = repository.getPublished();
const sorted = [...published].sort((left, right) => right.views - left.views);
const groups = groupByCategory(sorted);
return {
statistics,
groups,
html: sorted.map(renderArticleCard).join("\n\n"),
};
}
async function main() {
const repository = new ArticleRepository(articles);
repository.update(103, { published: true, views: 500 });
const report = await createReport(repository);
console.log("文章统计:", JSON.stringify(report.statistics, null, 2));
console.log("分类结果:", Object.keys(report.groups).join(" / "));
console.log("HTML 预览:\n", report.html);
console.log("字符转义:", escapeHtml('<div title="测试">A & B</div>'));
// 超长行:检查横向滚动、复制完整性和行号是否保持对齐。
const previewUrl = "https://example.com/wordpress/theme/code-block/preview?language=javascript&test=horizontal-scroll&article=long-code-block&preserve_indentation=true&show_line_numbers=true&theme=light&message=中文与English混合内容";
console.log("预览地址:", previewUrl);
}
main().catch((error) => {
console.error("生成报告失败:", error.message);
});
这是 JavaScript 代码块结束后的正文。检查它是否正常显示,以及代码块与正文之间的间距。
CSS:164 行
共 164 行,其中 144 行非空代码。下面的整个代码块用于测试长内容显示。
/* 中文注释:示例文章卡片样式,仅作为代码块内容展示。 */
:root {
--page-bg: #f3f6fb;
--surface-bg: #ffffff;
--text-main: #1f2937;
--text-muted: #64748b;
--accent: #2563eb;
--border-color: #dbe3ee;
--card-radius: 16px;
--space-unit: 8px;
}
* {
box-sizing: border-box;
}
body {
margin: 0;
color: var(--text-main);
background: var(--page-bg);
font-family: system-ui, -apple-system, "Segoe UI", sans-serif;
font-size: 16px;
line-height: 1.7;
}
.page {
width: min(100% - 40px, 1120px);
margin-inline: auto;
padding-block: 48px;
}
.page__header {
display: flex;
align-items: end;
justify-content: space-between;
gap: 24px;
margin-bottom: 32px;
}
.page__title {
margin: 0;
font-size: clamp(28px, 4vw, 44px);
line-height: 1.2;
letter-spacing: -0.03em;
}
.page__description {
max-width: 60ch;
margin: 12px 0 0;
color: var(--text-muted);
}
.article-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 24px;
}
.article-card {
display: flex;
flex-direction: column;
gap: 12px;
padding: 24px;
border: 1px solid var(--border-color);
border-radius: var(--card-radius);
background: var(--surface-bg);
box-shadow: 0 8px 24px rgb(15 23 42 / 5%);
transition: transform 180ms ease, box-shadow 180ms ease;
}
.article-card:hover {
transform: translateY(-4px);
box-shadow: 0 16px 40px rgb(15 23 42 / 10%);
}
.article-card__category {
align-self: flex-start;
padding: 4px 10px;
border-radius: 999px;
color: var(--accent);
background: rgb(37 99 235 / 8%);
font-size: 12px;
font-weight: 600;
}
.article-card__title {
margin: 0;
font-size: 22px;
line-height: 1.45;
overflow-wrap: anywhere;
}
.article-card__meta {
margin: auto 0 0;
color: var(--text-muted);
font-variant-numeric: tabular-nums;
}
.article-card a {
color: inherit;
text-decoration-thickness: 1px;
text-underline-offset: 4px;
}
.article-card a:focus-visible {
outline: 3px solid var(--accent);
outline-offset: 4px;
border-radius: 4px;
}
.article-card::after {
content: "阅读更多 →";
color: var(--accent);
font-size: 14px;
}
/* 超长声明:用于检查代码块是否支持横向滚动。 */
.article-card[data-preview="long-line-test"] {
background-image: linear-gradient(135deg, rgba(37, 99, 235, 0.08) 0%, rgba(14, 165, 233, 0.06) 25%, rgba(99, 102, 241, 0.05) 50%, rgba(168, 85, 247, 0.04) 75%, rgba(255, 255, 255, 1) 100%);
}
@media (max-width: 900px) {
.article-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.page__header {
align-items: start;
flex-direction: column;
}
}
@media (max-width: 600px) {
.page {
width: calc(100% - 24px);
padding-block: 28px;
}
.article-grid {
grid-template-columns: minmax(0, 1fr);
gap: 16px;
}
.article-card {
padding: 20px;
}
}
@media (prefers-color-scheme: dark) {
:root {
--page-bg: #0f172a;
--surface-bg: #182235;
--text-main: #e2e8f0;
--text-muted: #a7b4c8;
--accent: #93c5fd;
--border-color: #334155;
}
}
@media (prefers-reduced-motion: reduce) {
.article-card {
transition: none;
}
.article-card:hover {
transform: none;
}
}
这是 CSS 代码块结束后的正文。检查它是否正常显示,以及代码块与正文之间的间距。
主题显示检查
- 检查三个代码块是否完整显示,底部是否出现截断。
- 如果主题提供行号,检查末尾行号是否与上方标注的总行数一致。
- 检查关键字、字符串、数字和中文注释的高亮颜色。
- 检查缩进和空行是否保留,行号是否与代码对齐。
- 检查超长行的横向滚动或自动换行表现。
- 如果主题提供复制按钮,检查复制后是否混入行号或丢失内容。
- 在移动端检查代码块是否撑宽整个页面。
- 如果主题支持明暗切换,检查两种模式下的文字对比度。
原创文章,作者:火鸡味锅巴,如若转载,请注明出处:https://www.xianou.com/69.html