Menu

[7e3fed]: / docs / _plugins / tocmaker_block.rb  Maximize  Restore  History

Download this file

61 lines (41 with data), 1.4 kB

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# Generates a table of contents based on markdown headers in the body
#
# The block has 2 optional args:
# * A variable name. If provided, the toc will only be generated if the var is true
# * An integer, describing the maximum depth at which headers are added to the toc
class TocMakerBlock < Liquid::Block
def initialize(tag_name, arg, tokens)
super
condition, depth = arg.split
@max_depth = depth.to_s.empty? ? 100 : depth.to_i
@condition_var = condition.strip unless condition.to_s.empty?
@body = tokens
end
def to_internal_link(header)
url = header.downcase.gsub(/[^a-zA-Z0-9 -]+/, "").strip.gsub(/\s+/, "-")
"[#{header}](##{url})"
end
def render(context)
contents = @body.render(context)
if @condition_var && !context[@condition_var]
# If the condition is false, the toc is not generated
return contents
end
headers = contents.lines.map {|l|
if /^(#+)\s+(\S.*)$/ =~ l
[$1.length, $2]
end
}.compact
min_indent = headers.map {|t| t[0]}.min
headers = headers.map {|t|
actual_depth = t[0] - min_indent
if actual_depth < @max_depth then
indent = " " * actual_depth
"#{indent}* #{to_internal_link(t[1])}"
end
}.compact
headers.unshift("### Table Of Contents\n")
headers.join("\n") + contents
end
end
Liquid::Template.register_tag('tocmaker', TocMakerBlock)
Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.