From c26d00db648a4b475d94c9ed8e21dafb6efa1776 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B8rn=20Erik=20Pedersen?= Date: Wed, 6 Nov 2019 09:20:59 +0100 Subject: [PATCH] hugolib: Fix ref/relref anhcor handling Fixes #6481 --- hugolib/shortcode_test.go | 65 ++++++++++++++++++++++++++++++++++++++- hugolib/site.go | 6 ++-- 2 files changed, 67 insertions(+), 4 deletions(-) diff --git a/hugolib/shortcode_test.go b/hugolib/shortcode_test.go index 36f004253..614b8f060 100644 --- a/hugolib/shortcode_test.go +++ b/hugolib/shortcode_test.go @@ -16,9 +16,10 @@ package hugolib import ( "fmt" "path/filepath" - "reflect" + "github.com/spf13/viper" + "github.com/gohugoio/hugo/parser/pageparser" "github.com/gohugoio/hugo/resources/page" @@ -1195,3 +1196,65 @@ Get: {{ printf "%v (%T)" $b1 $b1 | safeHTML }} "types string: - 0: true (string) - 1: trues (string) - 2: 33 (string) - 3: 3.14 (string) ", ) } + +func TestShortcodeRef(t *testing.T) { + for _, plainIDAnchors := range []bool{false, true} { + plainIDAnchors := plainIDAnchors + t.Run(fmt.Sprintf("plainIDAnchors=%t", plainIDAnchors), func(t *testing.T) { + t.Parallel() + + v := viper.New() + v.Set("baseURL", "https://example.org") + v.Set("blackfriday", map[string]interface{}{ + "plainIDAnchors": plainIDAnchors, + }) + + builder := newTestSitesBuilder(t).WithViper(v) + + for i := 1; i <= 2; i++ { + builder.WithContent(fmt.Sprintf("page%d.md", i), `--- +title: "Hugo Rocks!" +--- + + + +[Page 1]({{< ref "page1.md" >}}) +[Page 1 with anchor]({{< relref "page1.md#doc" >}}) +[Page 2]({{< ref "page2.md" >}}) +[Page 2 with anchor]({{< relref "page2.md#doc" >}}) + + +## Doc + + +`) + } + + builder.Build(BuildCfg{}) + + if plainIDAnchors { + builder.AssertFileContent("public/page2/index.html", + ` +Page 1 with anchor +Page 2 +Page 2 with anchor

+ +

Doc

+`, + ) + } else { + builder.AssertFileContent("public/page2/index.html", + ` +

Page 1 +Page 1 with anchor +Page 2 +Page 2 with anchor

+

Doc

+`, + ) + } + + }) + } + +} diff --git a/hugolib/site.go b/hugolib/site.go index fb5dee46b..b9ec64224 100644 --- a/hugolib/site.go +++ b/hugolib/site.go @@ -719,12 +719,12 @@ func (s *siteRefLinker) refLink(ref string, source interface{}, relative bool, o var link string if refURL.Path != "" { - target, err := s.s.getPageNew(p, refURL.Path) + var err error + target, err = s.s.getPageNew(p, refURL.Path) var pos text.Position if err != nil || target == nil { if p, ok := source.(text.Positioner); ok { pos = p.Position() - } } @@ -758,8 +758,8 @@ func (s *siteRefLinker) refLink(ref string, source interface{}, relative bool, o } if refURL.Fragment != "" { - _ = target link = link + "#" + refURL.Fragment + if pctx, ok := target.(pageContext); ok && !target.File().IsZero() && !pctx.getRenderingConfig().PlainIDAnchors { if refURL.Path != "" { link = link + ":" + target.File().UniqueID()