summaryrefslogtreecommitdiffstats
path: root/tpl/tplimpl/template.go
diff options
context:
space:
mode:
authorBjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>2020-01-30 20:02:26 +0100
committerBjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>2020-01-30 23:44:42 +0100
commitf45cb3172862140883cfa08bd401c17e1ada5b39 (patch)
tree7d900485b290433572df5b24158a2b38a644691e /tpl/tplimpl/template.go
parent49ef6472039ede7d485242eba511207a8274495a (diff)
Fix base template handling with preceding comments
Fixes #6816
Diffstat (limited to 'tpl/tplimpl/template.go')
-rw-r--r--tpl/tplimpl/template.go41
1 files changed, 35 insertions, 6 deletions
diff --git a/tpl/tplimpl/template.go b/tpl/tplimpl/template.go
index a87cdde34..457a5cb92 100644
--- a/tpl/tplimpl/template.go
+++ b/tpl/tplimpl/template.go
@@ -22,6 +22,8 @@ import (
"strings"
"sync"
"time"
+ "unicode"
+ "unicode/utf8"
"github.com/gohugoio/hugo/common/types"
@@ -72,13 +74,40 @@ var (
_ tpl.Info = (*templateState)(nil)
)
-// A template needing a base template is a template with only define sections,
-// but we check only for the start.
-// If a base template does not exist, we will handle that when it's used.
-var baseTemplateDefineRe = regexp.MustCompile(`^\s*{{-?\s*define`)
+var baseTemplateDefineRe = regexp.MustCompile(`^{{-?\s*define`)
+// needsBaseTemplate returns true if the first non-comment template block is a
+// define block.
+// If a base template does not exist, we will handle that when it's used.
func needsBaseTemplate(templ string) bool {
- return baseTemplateDefineRe.MatchString(templ)
+ idx := -1
+ inComment := false
+ for i := 0; i < len(templ); {
+ if !inComment && strings.HasPrefix(templ[i:], "{{/*") {
+ inComment = true
+ i += 4
+ } else if inComment && strings.HasPrefix(templ[i:], "*/}}") {
+ inComment = false
+ i += 4
+ } else {
+ r, size := utf8.DecodeRuneInString(templ[i:])
+ if !inComment {
+ if strings.HasPrefix(templ[i:], "{{") {
+ idx = i
+ break
+ } else if !unicode.IsSpace(r) {
+ break
+ }
+ }
+ i += size
+ }
+ }
+
+ if idx == -1 {
+ return false
+ }
+
+ return baseTemplateDefineRe.MatchString(templ[idx:])
}
func newIdentity(name string) identity.Manager {
@@ -549,7 +578,7 @@ func (t *templateHandler) addTemplateFile(name, path string) error {
return nil
}
- needsBaseof := !t.noBaseNeeded(name) && baseTemplateDefineRe.MatchString(tinfo.template)
+ needsBaseof := !t.noBaseNeeded(name) && needsBaseTemplate(tinfo.template)
if needsBaseof {
t.needsBaseof[name] = tinfo
return nil