Skip to content

Commit ebca0ff

Browse files
authored
Merge pull request #2275 from ZhenShuo2021/refactor/gallery
♻️ Refactor(gallery): improve readibility
2 parents b83889b + 43857a5 commit ebca0ff

File tree

1 file changed

+24
-36
lines changed

1 file changed

+24
-36
lines changed

layouts/shortcodes/gallery.html

Lines changed: 24 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,31 @@
11
{{ $id := delimit (slice "gallery" (partial "functions/uid.html" .)) "-" -}}
2-
3-
4-
<div id="{{- $id -}}" class="gallery">
5-
{{ $page := .Page -}}
6-
7-
8-
<!-- find all img tags -->
9-
{{ $imgTagRegex := `<img\s+[^>]*>` -}}
10-
{{ $imgTags := findRE $imgTagRegex .Inner -}}
11-
{{ $newContent := .Inner -}}
12-
13-
{{ range $imgTags -}}
14-
{{ $imgTag := . -}}
15-
<!-- extract src attribute -->
16-
{{ $srcRegex := `src=['"]([^'"]+)['"]` -}}
17-
{{ $srcMatches := findRESubmatch $srcRegex $imgTag -}}
18-
19-
{{ if $srcMatches -}}
20-
{{ $srcFull := index (index $srcMatches 0) 0 -}}
21-
{{ $src := index (index $srcMatches 0) 1 -}}
22-
23-
{{ $finalSrc := $src -}}
24-
{{ $isExternalURL := or (hasPrefix $src "http://") (hasPrefix $src "https://") -}}
25-
26-
{{ if $isExternalURL -}}
27-
{{ with resources.GetRemote $src -}}{{ $finalSrc = .RelPermalink -}}{{ end -}}
2+
{{ $content := .Inner -}}
3+
4+
{{/* find all img tags */}}
5+
{{ range findRE `<img\s+[^>]*>` $content -}}
6+
{{ $imgTag := . -}}
7+
{{/* extract src attribute */}}
8+
{{ with findRESubmatch `src=['"]([^'"]+)['"]` $imgTag -}}
9+
{{ $srcAttr := index (index . 0) 0 -}}
10+
{{ $srcValue := index (index . 0) 1 -}}
11+
{{ $srcValueFinal := $srcValue -}}
12+
13+
{{ if or (hasPrefix $srcValue "http://") (hasPrefix $srcValue "https://") -}}
14+
{{ with resources.GetRemote $srcValue -}}{{ $srcValueFinal = .RelPermalink -}}{{ end -}}
15+
{{ else -}}
16+
{{ with $.Page.Resources.GetMatch $srcValue -}}
17+
{{ $srcValueFinal = .RelPermalink -}}
2818
{{ else -}}
29-
{{ with $page.Resources.GetMatch $src -}}
30-
{{ $finalSrc = .RelPermalink -}}
31-
{{ else -}}
32-
{{ with resources.GetMatch $src -}}{{ $finalSrc = .RelPermalink }}{{ end -}}
33-
{{ end -}}
19+
{{ with resources.GetMatch $srcValue -}}{{ $srcValueFinal = .RelPermalink -}}{{ end -}}
3420
{{ end -}}
35-
36-
{{ $newSrc := printf `src="%s"` $finalSrc -}}
37-
{{ $newImg := replace $imgTag $srcFull $newSrc -}}
38-
{{ $newContent = replace $newContent $imgTag $newImg -}}
3921
{{ end -}}
22+
23+
{{ $newTag := replace $imgTag $srcAttr (printf `src="%s"` $srcValueFinal) -}}
24+
{{ $content = replace $content $imgTag $newTag -}}
4025
{{ end -}}
26+
{{ end -}}
27+
4128

42-
{{ $newContent | safeHTML -}}
29+
<div id="{{- $id -}}" class="gallery">
30+
{{ $content | safeHTML -}}
4331
</div>

0 commit comments

Comments
 (0)