我有一个基本的 Web 服务器,它从 JSON 帖子数据库中呈现博客帖子,其中主要段落是从 JSON 字符串数组构建的。我试图找到一种方法来轻松地对新行或换行符进行编码,但发现这些值的编码如何从 JSON 更改为 GoLang,最后更改为我的 HTML 网页时遇到了很多困难。当我尝试用换行符对我的 JSON 进行编码时,我发现我必须对它们进行编码\\n而不是仅仅\n为了让它们实际出现在我的页面上。然而,一个问题是它们只是作为文本出现,而不是换行符。


然后我尝试研究\n将连接的字符串数组的部分替换为<br>标签的方法,但是我找不到任何方法来使用 go 来执行此操作,并转向尝试在 javascript 中这样做。尽管我在我的 HTML 链接中推迟了对我的 javascript 的调用,但这也不起作用。这是那个javascript:


var title = window.document.getElementById("title");

var timestamp = window.document.getElementById("timestamp");

var sitemap = window.document.getElementById("sitemap");

var main = window.document.getElementById("main");

var contact_form = window.document.getElementById("contact-form");

var content_info = window.document.getElementById("content-info");


var str = main.innerHTML;


function replaceNewlines() {

    // Replace the \n with <br>

    str = str.replace(/(?:\r\n|\r|\n)/g, "<br>");


    // Update the value of paragraph

    main.innerHTML = str;

}

这是我的 HTML:


<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Dynamic JSON Events</title>

    <link rel="stylesheet" href="/blogtemplate.css"></style>

</head>

<body>

    <section id="title">

        <h1 id="text-title">{{.Title}}</h1>

        <time id="timestamp">

            {{.Timestamp}}

        </time>

    </section>

    <nav role="navigation" id="site-nav">

        <ul id="sitemap">

        </ul>

    </nav>

    <main role="main" id="main">

        {{.ParsedMain}}

    </main>

    <footer role="contentinfo" id="footer">

        <form id="contact-form" role="form">

        <address>

            Contact me by <a id="my-email" href="mailto:antonhibl11@gmail.com" class="my-email">e-mail</a>

        </address>

        </form>

    </footer>

<script defer src="/blogtemplate.js">

</script>

</body>

</html>

然后,我最终转而尝试将<br>标签硬编码到我的 json 数据中,发现当它最终到达浏览器时,它只是呈现为 < 和 >。我对这种编码过程感到非常沮丧,不断导致我在创建换行符和换行符时出现问题。如何在我的 JSON 字符串数据中轻松地包含我想要的换行符?