Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Templates golang模板转义第一个字符_Templates_Go - Fatal编程技术网

Templates golang模板转义第一个字符

Templates golang模板转义第一个字符,templates,go,Templates,Go,我正在尝试使用标准模板包构建站点地图XML文件。 但是第一个字符集“您的示例显示您使用的是html/template包,它会自动转义用于html的文本 如果您想要一个原始模板引擎,请使用text/template包,而html引擎只是用上下文感知转义将其包装起来 但是,您需要自己确保使用原始模板引擎输出的文本是XML安全的。您可以通过向模板公开一些escape函数,并通过该函数传递所有文本,而不是直接编写文本来做到这一点 [编辑]这看起来像是html/template中的一个bug,如果你在xm

我正在尝试使用标准模板包构建站点地图XML文件。

但是第一个字符集“您的示例显示您使用的是
html/template
包,它会自动转义用于html的文本

如果您想要一个原始模板引擎,请使用
text/template
包,而html引擎只是用上下文感知转义将其包装起来

但是,您需要自己确保使用原始模板引擎输出的文本是XML安全的。您可以通过向模板公开一些
escape
函数,并通过该函数传递所有文本,而不是直接编写文本来做到这一点

[编辑]这看起来像是
html/template
中的一个bug,如果你在xml声明中省略了
,它可以正常工作。但我的建议仍然有效——如果不是html,最好使用
文本/模板
包。实际上,更好的是,将站点地图描述为一个结构,而根本不使用模板,只使用xml序列化更新。

另请参见github上的问题12496,该问题确认他们不打算解决此问题

可能是因为这是HTML模板包,您正在尝试 我怀疑它不知道如何解析 有问号的指令

如果需要,您可能希望使用文本/模板包 不会利用任何HTML自动转义 特征


您使用的是
text/template
还是
html/template
?如果您想要一个向模板公开XML转义函数的示例,我会将其添加到我的答案中。我认为只有通过模板的值才是转义。因此我的错误。Thanks@AlexandreStein它实际上看起来像一个bug,但是使用文本/模板仍然可以修复它。
package main

import (
    "bytes"
    "fmt"
    "html/template"
)

const (
    tmplStr = `{{define "indexSitemap"}}<?xml version="1.0" encoding="UTF-8"?>
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<sitemap>
    <loc>https://www.test.com/sitemap.xml</loc>
</sitemap>
<sitemap>
    <loc>https://www.test.com/events-sitemap.xml</loc>
</sitemap>
<sitemap>
    <loc>https://www.test.com/gamesAndTeams-sitemap.xml</loc>
</sitemap>
</sitemapindex>{{end}}`
)

func main() {
    // Parse the template and check for error
    tmpl, parseErr := template.New("test").Parse(tmplStr)
    if parseErr != nil {
        fmt.Println(parseErr)
        return
    }

    // Init the writer
    buf := new(bytes.Buffer)

    // Execute and get the template error if any
    tmplExErr := tmpl.ExecuteTemplate(buf, "indexSitemap", nil)
    if tmplExErr != nil {
        fmt.Println(tmplExErr)
        return
    }

    // Print the content malformed
    fmt.Println(buf)
}