summaryrefslogtreecommitdiffstats
path: root/parser
diff options
context:
space:
mode:
authorBjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>2023-01-26 10:30:25 +0100
committerBjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>2023-01-26 11:41:07 +0100
commit168858331f5e9311e718410e55c4296313ce6b05 (patch)
treef15001a545c3015e688c4296f5c349b8b3da16c0 /parser
parent4ef9baf5bd24b6a105f78eba1147dad9ffabd82a (diff)
Fix shortcode detection in RenderString
Fixes #10654
Diffstat (limited to 'parser')
-rw-r--r--parser/pageparser/pageparser.go13
-rw-r--r--parser/pageparser/pageparser_test.go27
2 files changed, 40 insertions, 0 deletions
diff --git a/parser/pageparser/pageparser.go b/parser/pageparser/pageparser.go
index 0a9fc61af..768747907 100644
--- a/parser/pageparser/pageparser.go
+++ b/parser/pageparser/pageparser.go
@@ -19,6 +19,8 @@ import (
"fmt"
"io"
"io/ioutil"
+ "regexp"
+ "strings"
"github.com/gohugoio/hugo/parser/metadecoders"
)
@@ -234,3 +236,14 @@ func IsProbablySourceOfItems(source []byte, items Items) bool {
return true
}
+
+var hasShortcodeRe = regexp.MustCompile(`{{[%,<][^\/]`)
+
+// HasShortcode returns true if the given string contains a shortcode.
+func HasShortcode(s string) bool {
+ // Fast path for the common case.
+ if !strings.Contains(s, "{{") {
+ return false
+ }
+ return hasShortcodeRe.MatchString(s)
+}
diff --git a/parser/pageparser/pageparser_test.go b/parser/pageparser/pageparser_test.go
index a21b97970..de817d1fb 100644
--- a/parser/pageparser/pageparser_test.go
+++ b/parser/pageparser/pageparser_test.go
@@ -101,3 +101,30 @@ func TestIsProbablyItemsSource(t *testing.T) {
c.Assert(IsProbablySourceOfItems([]byte(`{{< foo >}} `), items), qt.IsFalse)
c.Assert(IsProbablySourceOfItems([]byte(``), items), qt.IsFalse)
}
+
+func TestHasShortcode(t *testing.T) {
+ c := qt.New(t)
+
+ c.Assert(HasShortcode("{{< foo >}}"), qt.IsTrue)
+ c.Assert(HasShortcode("aSDasd SDasd aSD\n\nasdfadf{{% foo %}}\nasdf"), qt.IsTrue)
+ c.Assert(HasShortcode("{{</* foo */>}}"), qt.IsFalse)
+ c.Assert(HasShortcode("{{%/* foo */%}}"), qt.IsFalse)
+
+}
+
+func BenchmarkHasShortcode(b *testing.B) {
+ withShortcode := strings.Repeat("this is text", 30) + "{{< myshortcode >}}This is some inner content.{{< /myshortcode >}}" + strings.Repeat("this is text", 30)
+ withoutShortcode := strings.Repeat("this is text", 30) + "This is some inner content." + strings.Repeat("this is text", 30)
+ b.Run("Match", func(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ HasShortcode(withShortcode)
+ }
+ })
+
+ b.Run("NoMatch", func(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ HasShortcode(withoutShortcode)
+ }
+ })
+
+}