获取GitHub文件内容时如何保留原有格式?
保留GitHub文件内容格式的解决方法
问题根源:HTML渲染时会自动合并连续的空格、换行符,直接用
document.write输出文本会丢失原始格式。基础解决方案:使用
<pre>标签包裹内容
针对直接获取raw文件的代码修改:fetch("https://raw.githubusercontent.com/Ayanmullick/test/master/AutomationAcc/test1.ps1") .then(response => response.text()) .then(data => { const preElement = document.createElement('pre'); preElement.textContent = data; document.body.appendChild(preElement); })针对GitHub REST API的代码修改:
fetch("https://api.github.com/repos/Ayanmullick/test/git/blobs/97e69f38b60f360dc8a22e07c6c395feb0e004a8") .then(response => response.json()) .then(data => atob(data.content)) .then(decoded => { const preElement = document.createElement('pre'); preElement.textContent = decoded; document.body.appendChild(preElement); })进阶:添加语法高亮
如果需要给代码添加语法高亮,可以结合<code>标签和语法高亮库(如Prism.js):fetch("https://raw.githubusercontent.com/Ayanmullick/test/master/AutomationAcc/test1.ps1") .then(response => response.text()) .then(data => { const preElement = document.createElement('pre'); const codeElement = document.createElement('code'); codeElement.className = 'language-powershell'; // 指定语言类型 codeElement.textContent = data; preElement.appendChild(codeElement); document.body.appendChild(preElement); // 若引入了Prism.js,调用高亮方法 // Prism.highlightElement(codeElement); })
内容的提问来源于stack exchange,提问作者Ayan Mullick
相关产品推荐
相关产品推荐

