Skip to content

Commit fec49da

Browse files
authored
Fix images paths in several situations related to pages in subdirs (#83)
1 parent f77ee1d commit fec49da

File tree

2 files changed

+87
-1
lines changed

2 files changed

+87
-1
lines changed

helpers.go

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"errors"
55
"fmt"
66
"html/template"
7+
"path"
78
"slices"
89
"strings"
910
"time"
@@ -160,7 +161,17 @@ func Banner(p Page) string {
160161
return ""
161162
}
162163

163-
return string(image.Destination)
164+
dest := string(image.Destination)
165+
if len(dest) == 0 || dest == "#" {
166+
return ""
167+
}
168+
169+
if !(path.IsAbs(dest) || strings.HasPrefix(dest, "http")) {
170+
d := path.Dir(p.FileName())
171+
dest = path.Join("/", d, dest)
172+
}
173+
174+
return dest
164175
}
165176

166177
func Emoji(p Page) string {

helpers_test.go

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
package xlog
2+
3+
import (
4+
"testing"
5+
"time"
6+
7+
"github.com/stretchr/testify/require"
8+
"github.com/yuin/goldmark/text"
9+
)
10+
11+
func TestBanner(t *testing.T) {
12+
tcs := []struct {
13+
name string
14+
path string
15+
content string
16+
expected string
17+
}{
18+
{
19+
name: "page in root and image is relative implicitly",
20+
path: "home",
21+
content: "![](image.jpg)",
22+
expected: "/image.jpg",
23+
},
24+
{
25+
name: "page in root and image is relative explicitly",
26+
path: "home",
27+
content: "![](./image.jpg)",
28+
expected: "/image.jpg",
29+
},
30+
{
31+
name: "page in root and image is relative explicitly in subdir",
32+
path: "home",
33+
content: "![](./images/image.jpg)",
34+
expected: "/images/image.jpg",
35+
},
36+
{
37+
name: "page in subdir and image is relative implicitly",
38+
path: "posts/home",
39+
content: "![](image.jpg)",
40+
expected: "/posts/image.jpg",
41+
},
42+
{
43+
name: "page in subdir and image is relative explicitly",
44+
path: "posts/home",
45+
content: "![](./image.jpg)",
46+
expected: "/posts/image.jpg",
47+
},
48+
{
49+
name: "page in subdir and image is relative explicitly in subdir",
50+
path: "posts/home",
51+
content: "![](./images/image.jpg)",
52+
expected: "/posts/images/image.jpg",
53+
},
54+
{
55+
name: "page in subdir and image is relative explicitly in parent",
56+
path: "posts/home",
57+
content: "![](../images/image.jpg)",
58+
expected: "/images/image.jpg",
59+
},
60+
}
61+
62+
for _, tc := range tcs {
63+
t.Run(tc.name, func(t *testing.T) {
64+
reader := text.NewReader([]byte(tc.content))
65+
p := page{
66+
name: tc.path,
67+
lastUpdate: time.Time{},
68+
ast: MarkdownConverter().Parser().Parse(reader),
69+
content: (*Markdown)(&tc.content),
70+
}
71+
72+
require.Equal(t, tc.expected, Banner(&p))
73+
})
74+
}
75+
}

0 commit comments

Comments
 (0)