poll,md: adds pclink for polls

This commit is contained in:
Eldeberen 2021-02-20 17:17:33 +01:00
parent b08085d54e
commit 9d08f81342
Signed by untrusted user: Darks
GPG Key ID: 7515644268BE1433
3 changed files with 79 additions and 0 deletions

View File

@ -37,3 +37,5 @@
{% endif %}
</div>
{% endmacro %}
{{ wpoll(poll) if poll }}

View File

@ -5,6 +5,8 @@ from markdown.extensions.codehilite import CodeHiliteExtension
from markdown.extensions.footnotes import FootnoteExtension
from markdown.extensions.toc import TocExtension
from app.utils.markdown_extensions.pclinks import PCLinkExtension
@app.template_filter('md')
def md(text):
@ -22,6 +24,7 @@ def md(text):
CodeHiliteExtension(linenums=True, use_pygments=True),
FootnoteExtension(UNIQUE_IDS=True),
TocExtension(baselevel=2),
PCLinkExtension(),
]
def escape(text):

View File

@ -0,0 +1,74 @@
'''
PClinks Extension for Python-Markdown
======================================
Converts [[type:id]] to relative links.
Based on <https://Python-Markdown.github.io/extensions/wikilinks>.
Original code Copyright [Waylan Limberg](http://achinghead.com/).
License: [BSD](https://opensource.org/licenses/bsd-license.php)
'''
from markdown.extensions import Extension
from markdown.inlinepatterns import InlineProcessor
import xml.etree.ElementTree as etree
from flask import url_for, render_template
from app.models.poll import Poll
class PCLinkExtension(Extension):
def __init__(self, **kwargs):
self.config = {
# 'base_url': ['/', 'String to append to beginning or URL.'],
# 'end_url': ['/', 'String to append to end of URL.'],
# 'html_class': ['pclink', 'CSS hook. Leave blank for none.'],
}
super().__init__(**kwargs)
def extendMarkdown(self, md):
self.md = md
# append to end of inline patterns
PCLINK_RE = r'\[\[([a-z]+):\W?(\w+)\]\]'
pclinkPattern = PCLinksInlineProcessor(PCLINK_RE, self.getConfigs())
pclinkPattern.md = md
md.inlinePatterns.register(pclinkPattern, 'pclink', 75)
class PCLinksInlineProcessor(InlineProcessor):
def __init__(self, pattern, config):
super().__init__(pattern)
self.config = config
self.handles = {
'poll': handlePoll,
}
def handleMatch(self, m, data):
link_type = m.group(1).strip()
if link_type in self.handles:
content_id = m.group(2).strip()
a = self.handles[link_type](content_id, data)
else:
a = ''
return a, m.start(0), m.end(0)
def handlePoll(content_id, context):
print(context)
if not context.startswith("[[") or not context.endswith("]]"):
return "[Sondage invalide]"
try:
id = int(content_id)
except ValueError:
return "[ID du sondage invalide]"
poll = Poll.query.get(content_id)
if poll is None:
return "[Sondage non trouvé]"
html = render_template('widgets/poll.html', poll=poll)
html = html.replace('\n', '') # Needed to avoid lots of <br> due to etree
return etree.fromstring(html)