-
Notifications
You must be signed in to change notification settings - Fork 6
/
lightgallery.py
61 lines (50 loc) · 2.45 KB
/
lightgallery.py
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
61
from markdown import Extension
from markdown.treeprocessors import Treeprocessor
from markdown.util import etree
import re
class ImagesTreeprocessor(Treeprocessor):
def __init__(self, config, md):
Treeprocessor.__init__(self, md)
self.re = re.compile(r'^!.*')
self.config = config
def run(self, root):
parent_map = {c: p for p in root.iter() for c in p}
try:
images = root.iter("img")
except AttributeError:
images = root.getiterator("img")
for image in images:
desc = image.attrib["alt"]
if self.re.match(desc):
desc = desc.lstrip("!")
image.set("alt", desc)
parent = parent_map[image]
ix = list(parent).index(image)
div_node = etree.Element('div')
div_node.set("class", "lightgallery")
new_node = etree.Element('a')
new_node.set("href", image.attrib["src"])
if self.config["show_description_in_lightgallery"]:
new_node.set("data-sub-html", desc)
new_node.append(image)
div_node.append(new_node)
parent.insert(ix, div_node)
parent.remove(image)
if self.config["show_description_as_inline_caption"]:
inline_caption_node = etree.Element('p')
inline_caption_node.set("class", self.config["custom_inline_caption_css_class"])
inline_caption_node.text = desc
parent.insert(ix + 1, inline_caption_node)
class LightGalleryExtension(Extension):
def __init__(self, **kwargs):
self.config = {
'show_description_in_lightgallery' : [True, 'Adds the description as caption in lightgallery dialog. Default: True'],
'show_description_as_inline_caption' : [False, 'Adds the description as inline caption below the image. Default: False'],
'custom_inline_caption_css_class' : ['', 'Custom CSS classes which are applied to the inline caption paragraph. Multiple classes are separated via space. Default: empty']
}
super(LightGalleryExtension, self).__init__(**kwargs)
def extendMarkdown(self, md, md_globals):
config = self.getConfigs()
md.treeprocessors.add("lightbox", ImagesTreeprocessor(config, md), "_end")
def makeExtension(*args, **kwargs):
return LightGalleryExtension(**kwargs)