Widget:Test
刷
历
编
跳到导航
跳到搜索
<script> document.addEventListener('DOMContentLoaded', function() {
// 1. 定位容器
const containerClass = mw.config.get('wgWidgetParams').containerClass;
const container = document.querySelector('.' + containerClass);
if (!container) {
console.error('SVG容器未找到');
return;
}
// 2. 解析基础参数
const params = {
width: container.dataset.svgWidth,
height: container.dataset.svgHeight,
path: container.dataset.svgPath,
fill: container.dataset.svgFill,
stroke: container.dataset.svgStroke,
strokeWidth: container.dataset.svgStrokeWidth,
foWidth: container.dataset.foWidth,
foHeight: container.dataset.foHeight,
foParams: JSON.parse(container.dataset.foParams || '[]') // 反序列化foreignObject参数
};
// 3. 动态创建SVG元素
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("width", params.width);
svg.setAttribute("height", params.height);
svg.setAttribute("viewBox", `0 0 ${params.width} ${params.height}`);
svg.setAttribute("xmlns", "http://www.w3.org/2000/svg");
// 4. 添加path元素
const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
path.setAttribute("d", params.path);
path.setAttribute("fill", params.fill);
path.setAttribute("stroke", params.stroke);
path.setAttribute("stroke-width", params.strokeWidth);
svg.appendChild(path);
// 5. 循环添加foreignObject及模板内容
params.foParams.forEach(fo => {
const foreignObj = document.createElementNS("http://www.w3.org/2000/svg", "foreignObject");
foreignObj.setAttribute("x", fo.x);
foreignObj.setAttribute("y", fo.y);
foreignObj.setAttribute("width", params.foWidth);
foreignObj.setAttribute("height", params.foHeight);
// 解析模板内容(通过MediaWiki的API获取模板渲染结果)
// 注意:需确保模板名和参数正确,这里用mw.html实体化模板
const templateHtml = mw.html.encode(`{{${fo.template}}}`); // 编码模板调用
foreignObj.innerHTML = `
${templateHtml}
`;
svg.appendChild(foreignObj); });
// 6. 将生成的SVG添加到容器 container.appendChild(svg);
}); </script>

沪公网安备 31011002002714 号