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

无差异字符串在Diff2HtmlUI中完整渲染的实现问题

解决Diff2Html渲染相同内容JSON时仅显示标题的问题

当两个JSON内容完全相同时,diff.createTwoFilesPatch生成的diff字符串只有文件头,没有内容差异块,Diff2Html默认不会渲染无差异的内容区域,所以只会显示标题。以下两种方法可以实现渲染完整内容:

方法一:修改diff字符串,补全内容块

手动判断生成的diff是否为空(无@@标记行),如果是,就拼接一个包含全部原内容的unified diff格式块,让Diff2Html能识别并渲染:

const diffString = diff.createTwoFilesPatch('file', 'file', this.reference, this.result, undefined, undefined, {
  context: Number.MAX_SAFE_INTEGER,
});

// 判断是否为无内容的空diff
const isEmptyDiff = !diffString.includes('@@');
let processedDiff = diffString;

if (isEmptyDiff) {
  const content = this.reference;
  const contentLines = content.split('\n');
  const lineCount = contentLines.length;
  // 构建符合unified diff规范的内容块
  const contentBlock = `@@ -1,${lineCount} +1,${lineCount} @@\n${contentLines.join('\n')}`;
  // 拼接到原diff字符串后
  processedDiff = diffString.trim() + '\n' + contentBlock;
}

// 用处理后的diff渲染
const div: HTMLElement = this.diffDiv.nativeElement;
const diff2htmlUi = new Diff2HtmlUI(div, processedDiff, this.configuration);
diff2htmlUi.draw();

方法二:直接在容器中添加原内容元素

如果不想修改diff字符串,可以直接判断空diff的情况,手动创建元素显示原内容:

const diffString = diff.createTwoFilesPatch('file', 'file', this.reference, this.result, undefined, undefined, {
  context: Number.MAX_SAFE_INTEGER,
});

const div: HTMLElement = this.diffDiv.nativeElement;
const isEmptyDiff = !diffString.includes('@@');

if (isEmptyDiff) {
  // 创建pre标签显示原内容,样式匹配Diff2Html风格
  const contentEl = document.createElement('pre');
  contentEl.textContent = this.reference;
  contentEl.style.margin = '1rem';
  contentEl.style.padding = '0.75rem';
  contentEl.style.backgroundColor = '#f6f8fa';
  contentEl.style.borderRadius = '6px';
  div.appendChild(contentEl);
} else {
  const diff2htmlUi = new Diff2HtmlUI(div, diffString, this.configuration);
  diff2htmlUi.draw();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 13:03:19