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

获取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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 14:35:39