diff --git a/blog/templates/blog/post.html b/blog/templates/blog/post.html index 39b1779..0934ff1 100644 --- a/blog/templates/blog/post.html +++ b/blog/templates/blog/post.html @@ -1,10 +1,7 @@

{% if title_links %}{% endif %}{{ post.title }}{% if title_links %}{% else %}
{% endif %}

{{ post.created_at|date:'m-d-Y :: H:i' }} by {{ post.user.first_name }} {{ post.user.last_name }}

- {% comment %} {{ post.content|insert_code_chunks }} - {% endcomment %} - {{ post.content|safe }} {% if post.tags.all %}

Tags: {% for tag in post.tags.all %} diff --git a/blog/templatetags/code_chunks.py b/blog/templatetags/code_chunks.py index 9b21487..4b66b4a 100644 --- a/blog/templatetags/code_chunks.py +++ b/blog/templatetags/code_chunks.py @@ -1,11 +1,12 @@ from django import template from django.template.defaultfilters import stringfilter from django.utils.safestring import mark_safe -import logging +import logging, re from pygments import highlight from pygments.lexers import get_lexer_by_name from pygments.formatters import HtmlFormatter from gergelypolonkaiweb.solarized_dark import SolarizedDarkStyle +from blog.models import CodeChunk register = template.Library() @@ -27,6 +28,48 @@ def hilite(language, code): formatter = CodeFormatter(style = SolarizedDarkStyle, linenos = False, cssclass = language + " code", noclasses = True) return highlight(code, lexer, formatter) +@register.filter(needs_autoescape=True) +@stringfilter +def insert_code_chunks(value, autoescape=None): + p = re.compile('\[\$ code:(?P[^:]+):(?P[^ ]+) \$\]') + i = p.finditer(value) + diff = 0 + + for match in i: + end, start = match.span() + oldlen = start - end + start += diff + end += diff + try: + chunk = CodeChunk.objects.get(language = match.group('lang'), slug = match.group('slug')) + # TODO: This is an ugly hack, as it includes template logic in code. BAD! + newstr = "

" + hilite(match.group('lang'), chunk.content) + "
" + except CodeChunk.DoesNotExist: + newstr = "" + + newlen = len(newstr) + value = value[:end] + newstr + value[start:] + diff += newlen - oldlen + + p = re.compile('\[\$ code:(?P[^:]+):(?P.+?) \$\]', re.DOTALL) + i = p.finditer(value) + diff = 0 + + for match in i: + end, start = match.span() + oldlen = start - end + start += diff + end += diff + + # TODO: This is an ugly hack, as it includes template logic in code. BAD! + newstr = "
" + hilite(match.group('lang'), match.group('code')) + "
" + + newlen = len(newstr) + value = value[:end] + newstr + value[start:] + diff += newlen - oldlen + + return mark_safe(value) + @register.filter(needs_autoescape=True) @stringfilter def syhilite(value, language, autoescape=None):