forked from DGNum/gestiojeux
53 lines
1.7 KiB
Python
53 lines
1.7 KiB
Python
|
import markdown
|
||
|
from django.template.loader import get_template
|
||
|
from .models import Category, Tag, Game
|
||
|
|
||
|
|
||
|
class InventoryLinkProcessor(markdown.inlinepatterns.InlineProcessor):
|
||
|
model = None
|
||
|
pattern = None
|
||
|
context_object_name = "object"
|
||
|
template_name = None
|
||
|
|
||
|
def __init__(self, md):
|
||
|
super().__init__(self.pattern, md)
|
||
|
|
||
|
def handleMatch(self, m, data):
|
||
|
template = get_template(self.template_name)
|
||
|
object_instance = self.model.objects.get(slug=m.group(1))
|
||
|
html = template.render({self.context_object_name: object_instance})
|
||
|
placeholder = self.md.htmlStash.store(html)
|
||
|
return placeholder, m.start(0), m.end(0)
|
||
|
|
||
|
|
||
|
class CategoryLinkProcessor(InventoryLinkProcessor):
|
||
|
model = Category
|
||
|
pattern = r"\[\[category:([\w-]+)\]\]"
|
||
|
context_object_name = "category"
|
||
|
template_name = "inventory/partials/category_item.html"
|
||
|
|
||
|
|
||
|
class TagLinkProcessor(InventoryLinkProcessor):
|
||
|
model = Tag
|
||
|
pattern = r"\[\[tag:([\w-]+)\]\]"
|
||
|
context_object_name = "tag"
|
||
|
template_name = "inventory/partials/tag_item.html"
|
||
|
|
||
|
|
||
|
class GameLinkProcessor(InventoryLinkProcessor):
|
||
|
model = Game
|
||
|
pattern = r"\[\[game:([\w-]+)\]\]"
|
||
|
context_object_name = "game"
|
||
|
template_name = "inventory/partials/game_item.html"
|
||
|
|
||
|
|
||
|
class InventoryMarkdownExtension(markdown.extensions.Extension):
|
||
|
def extendMarkdown(self, md):
|
||
|
md.inlinePatterns.register(CategoryLinkProcessor(md), "category_link", 75)
|
||
|
md.inlinePatterns.register(TagLinkProcessor(md), "tag_link", 75)
|
||
|
md.inlinePatterns.register(GameLinkProcessor(md), "game_link", 75)
|
||
|
|
||
|
|
||
|
def makeExtension(**kwargs):
|
||
|
return InventoryMarkdownExtension(**kwargs)
|