Skip to content

Commit 9783f2b

Browse files
committed
Add plugin: redirect_with_metadata #72
1 parent 1681385 commit 9783f2b

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

_plugins/redirect_with_metadata.rb

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
module Jekyll
2+
class RedirectWithMetadata < Generator
3+
priority :lowest
4+
5+
def generate(site)
6+
redirect_map = build_redirect_map(site)
7+
8+
redirect_pages = site.pages.select { |page| page.data['redirect'] }
9+
redirect_pages.each do |page|
10+
target = redirect_map[normalize_url(page.data['redirect']['to'], site)]
11+
copy_metadata(from: target, to: page) if target
12+
end
13+
end
14+
15+
private
16+
17+
def build_redirect_map(site)
18+
pages_with_redirect_from = (site.pages + site.documents).select { |p| p.data['redirect_from'] }
19+
pages_with_redirect_from.flat_map do |page|
20+
[page.url, page.data['permalink']].compact.map { |u| [u.chomp('/'), page] }
21+
end.to_h
22+
end
23+
24+
def normalize_url(url, site)
25+
url.sub(site.config['url'] || '', '')
26+
.sub(site.config['baseurl'] || '', '')
27+
.chomp('/')
28+
end
29+
30+
def copy_metadata(from:, to:)
31+
from.data.each do |key, value|
32+
to.data[key] = value unless %w[layout redirect redirect_from permalink].include?(key)
33+
end
34+
end
35+
end
36+
end

0 commit comments

Comments
 (0)