tpl: Fix BOM issue in templates
authorBjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>
Tue, 30 Oct 2018 16:36:05 +0000 (17:36 +0100)
committerBjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>
Tue, 30 Oct 2018 17:12:14 +0000 (18:12 +0100)
Fixes #4895

hugolib/template_test.go
tpl/tplimpl/template.go

index eed3ee8ed9f36a4dede91b4be1d727708110f635..9cc523cb06323d5d5c15e0e68011bdb4b80bca30 100644 (file)
@@ -212,3 +212,27 @@ Some content
 
        }
 }
+
+// https://github.com/gohugoio/hugo/issues/4895
+func TestTemplateBOM(t *testing.T) {
+
+       b := newTestSitesBuilder(t).WithSimpleConfigFile()
+       bom := "\ufeff"
+
+       b.WithTemplatesAdded(
+               "_default/baseof.html", bom+`
+               Base: {{ block "main" . }}base main{{ end }}`,
+               "_default/single.html", bom+`{{ define "main" }}Hi!?{{ end }}`)
+
+       b.WithContent("page.md", `---
+title: "Page"
+---
+
+Page Content
+`)
+
+       b.CreateSites().Build(BuildCfg{})
+
+       b.AssertFileContent("public/page/index.html", "Base: Hi!?")
+
+}
index 8a26ce0e1f83bca48db01f80f4a621fefb234705..144bafdd8d819161609454650b5b7458fbe5dea0 100644 (file)
@@ -655,6 +655,22 @@ func (t *textTemplates) handleMaster(name, overlayFilename, masterFilename strin
 
 }
 
+func removeLeadingBOM(s string) string {
+       const bom = '\ufeff'
+
+       for i, r := range s {
+               if i == 0 && r != bom {
+                       return s
+               }
+               if i > 0 {
+                       return s[i:]
+               }
+       }
+
+       return s
+
+}
+
 func (t *templateHandler) addTemplateFile(name, baseTemplatePath, path string) error {
        t.checkState()
 
@@ -666,7 +682,8 @@ func (t *templateHandler) addTemplateFile(name, baseTemplatePath, path string) e
                if err != nil {
                        return templateInfo{filename: filename, fs: fs}, err
                }
-               s := string(b)
+
+               s := removeLeadingBOM(string(b))
 
                realFilename := filename
                if fi, err := fs.Stat(filename); err == nil {