html: Support pretty relative links

Hugo defaults to serving files with pretty urls [1] - this means
`/posts/foo.org` is served at `/posts/foo/`. This works because servers
default to serving index.html when a directory is specified and hugo renders
the post to `/posts/foo/index.html` instead of `/posts/foo.html`. To make
relative links work we need to (1) remove the fake `foo/` subdirectory from
unrooted links and (2) replace any `.org` suffix with `/`.

[1] https://gohugo.io/content-management/urls/#pretty-urls
This commit is contained in:
Niklas Fasching 2021-01-02 19:37:17 +01:00
parent 84d56e9562
commit 5dadf8c4c2
2 changed files with 38 additions and 3 deletions

View file

@ -42,3 +42,30 @@ func TestExtendedHTMLWriter(t *testing.T) {
t.Errorf("WriteText method of extending writer was not called: CallCount %d", extendedWriter.callCount)
}
}
var prettyRelativeLinkTests = map[string]string{
"[[/hello.org][hello]]": `<p><a href="/hello/">hello</a></p>`,
"[[hello.org][hello]]": `<p><a href="../hello/">hello</a></p>`,
"[[file:/hello.org]]": `<p><a href="/hello/">/hello/</a></p>`,
"[[file:hello.org]]": `<p><a href="../hello/">../hello/</a></p>`,
"[[http://hello.org]]": `<p><a href="http://hello.org">http://hello.org</a></p>`,
"[[/foo.png]]": `<p><img src="/foo.png" alt="/foo.png" title="/foo.png" /></p>`,
"[[foo.png]]": `<p><img src="../foo.png" alt="../foo.png" title="../foo.png" /></p>`,
"[[/foo.png][foo]]": `<p><a href="/foo.png">foo</a></p>`,
"[[foo.png][foo]]": `<p><a href="../foo.png">foo</a></p>`,
}
func TestPrettyRelativeLinks(t *testing.T) {
for org, expected := range prettyRelativeLinkTests {
t.Run(org, func(t *testing.T) {
writer := NewHTMLWriter()
writer.PrettyRelativeLinks = true
actual, err := New().Silent().Parse(strings.NewReader(org), "./prettyRelativeLinkTests.org").Write(writer)
if err != nil {
t.Errorf("%s\n got error: %s", org, err)
} else if actual := strings.TrimSpace(actual); actual != expected {
t.Errorf("%s:\n%s'", org, diff(actual, expected))
}
})
}
}