Skip to content

Commit 81e1083

Browse files
authored
Merge pull request #47620 from Andygol/render-link
Implementation of the Link Decorator function for processing localised links 🈂️
2 parents 88a3838 + a0ede94 commit 81e1083

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
{{- $u := urls.Parse .Destination -}}
2+
{{- $href := $u.String -}}
3+
{{- $langCode := .Page.Site.Language.Lang -}}
4+
5+
{{- if strings.HasPrefix $u.String "#" }}
6+
{{- /* Anchor link in the document, leave unchanged */ -}}
7+
8+
{{- else if $u.IsAbs -}}
9+
{{- /* External link, leave unchanged */ -}}
10+
11+
{{- else if strings.HasPrefix $u.Path (printf "/%s/" $langCode) -}}
12+
{{- /* Internal link in the current language, leave unchanged */ -}}
13+
14+
{{- else if strings.HasPrefix $u.Path "/" -}}
15+
{{- $localizedPath := printf "/%s%s" $langCode $u.Path -}}
16+
{{- with or
17+
(.Page.GetPage $localizedPath)
18+
(.Page.Resources.Get $localizedPath)
19+
(resources.Get $localizedPath)
20+
-}}
21+
{{- $href = .RelPermalink -}}
22+
{{- else -}}
23+
{{- $path := strings.TrimPrefix "./" $u.Path }}
24+
{{- with or
25+
(.Page.GetPage $path)
26+
(.Page.Resources.Get $path)
27+
(resources.Get $path)
28+
-}}
29+
{{- $href = .RelPermalink -}}
30+
{{- end -}}
31+
{{- end -}}
32+
33+
{{- if and $u.RawQuery (not (strings.Contains $href "?")) -}}
34+
{{- $href = printf "%s?%s" $href $u.RawQuery -}}
35+
{{- end -}}
36+
{{- if and $u.Fragment (not (strings.Contains $href "#")) -}}
37+
{{- $href = printf "%s#%s" $href $u.Fragment -}}
38+
{{- end -}}
39+
40+
{{- else -}}
41+
{{- /* Other internal links, leave unchanged */ -}}
42+
43+
{{- end -}}
44+
45+
{{- $attributes := dict "href" $href "title" (.Title | transform.HTMLEscape) -}}
46+
<a
47+
{{- range $k, $v := $attributes -}}
48+
{{- if $v -}}
49+
{{- printf " %s=%q" $k $v | safeHTMLAttr -}}
50+
{{- end -}}
51+
{{- end -}}
52+
>{{ .Text | safeHTML }}</a>
53+
{{- /**/ -}}

0 commit comments

Comments
 (0)