board.py
96 lines
| 2.7 KiB
| text/x-python
|
PythonLexer
|
r1000 | import re | ||
|
r1986 | from django import template | ||
|
r320 | from django.shortcuts import get_object_or_404 | ||
|
r1786 | from django.utils.text import re_tag | ||
from boards.mdx_neboard import LINE_BREAK_HTML | ||||
|
r1000 | |||
|
r1027 | IMG_ACTION_URL = '[<a href="{}">{}</a>]' | ||
|
r1786 | REGEX_NEWLINE = re.compile(LINE_BREAK_HTML) | ||
TRUNCATOR = '...' | ||||
HTML4_SINGLETS =( | ||||
'br', 'col', 'link', 'base', 'img', 'param', 'area', 'hr', 'input' | ||||
) | ||||
|
r1027 | |||
|
r692 | |||
|
r320 | register = template.Library() | ||
@register.simple_tag(name='post_url') | ||||
def post_url(*args, **kwargs): | ||||
post_id = args[0] | ||||
|
r692 | post = get_object_or_404('Post', id=post_id) | ||
|
r320 | |||
|
r1160 | return post.get_absolute_url() | ||
|
r614 | |||
|
r1648 | @register.inclusion_tag('boards/post.html', name='post_view', takes_context=True) | ||
|
r1390 | def post_view(context, post, *args, **kwargs): | ||
kwargs['perms'] = context['perms'] | ||||
|
r1648 | return post.get_view_params(*args, **kwargs) | ||
|
r614 | |||
|
r1650 | |||
|
r1377 | @register.simple_tag(name='page_url') | ||
def page_url(paginator, page_number, *args, **kwargs): | ||||
|
r1379 | if paginator.supports_urls(): | ||
return paginator.get_page_url(page_number) | ||||
|
r1786 | |||
@register.filter(name='truncatenewlines_html') | ||||
def truncatenewlines_html(value, arg): | ||||
|
r1799 | end_pos = 0 | ||
start_pos = 0 | ||||
|
r1786 | match_count = 0 | ||
# Collect places for truncation | ||||
while match_count <= arg: | ||||
|
r1799 | m = REGEX_NEWLINE.search(value, end_pos) | ||
|
r1786 | if m is None: | ||
break | ||||
else: | ||||
match_count += 1 | ||||
|
r1799 | end_pos = m.end() | ||
start_pos = m.start() | ||||
|
r1786 | |||
# Find and close open tags | ||||
if match_count > arg: | ||||
|
r1799 | truncate_pos = start_pos | ||
|
r1786 | |||
open_tags = [] | ||||
text = value[:truncate_pos] | ||||
current_pos = 0 | ||||
while True: | ||||
tag = re_tag.search(text, current_pos) | ||||
if tag is None: | ||||
break | ||||
else: | ||||
closing_tag, tagname, self_closing = tag.groups() | ||||
tagname = tagname.lower() | ||||
if self_closing or tagname in HTML4_SINGLETS: | ||||
pass | ||||
elif closing_tag: | ||||
# Check for match in open tags list | ||||
try: | ||||
i = open_tags.index(tagname) | ||||
except ValueError: | ||||
pass | ||||
else: | ||||
# SGML: An end tag closes, back to the matching start tag, | ||||
# all unclosed intervening start tags with omitted end tags | ||||
open_tags = open_tags[i + 1:] | ||||
else: | ||||
# Add it to the start of the open tags list | ||||
open_tags.insert(0, tagname) | ||||
current_pos = tag.end() | ||||
|
r1788 | if not text.endswith(TRUNCATOR): | ||
text += TRUNCATOR | ||||
|
r1786 | for tag in open_tags: | ||
|
r1792 | text += '</{}>'.format(tag) | ||
|
r1786 | else: | ||
text = value | ||||
return text | ||||