helpers.py 1.91 KB
Newer Older
Rocky Duan committed
1
from django.core.urlresolvers import reverse
2
from django.conf import settings
Rocky Duan committed
3
from mitxmako.shortcuts import render_to_string
4
from mustache_helpers import mustache_helpers
Rocky Duan committed
5
from django.core.urlresolvers import reverse
6 7
from functools import partial

8
from utils import *
Arjun Singh committed
9
import django_comment_client.settings as cc_settings
10

11
import pystache_custom as pystache
Rocky Duan committed
12
import urllib
13
import os
Rocky Duan committed
14 15

def pluralize(singular_term, count):
Rocky Duan committed
16
    if int(count) >= 2 or int(count) == 0:
Rocky Duan committed
17 18 19
        return singular_term + 's'
    return singular_term

20 21
# TODO there should be a better way to handle this
def include_mustache_templates():
22
    mustache_dir = settings.PROJECT_ROOT / 'templates' / 'discussion' / 'mustache'
23 24 25
    valid_file_name = lambda file_name: file_name.endswith('.mustache')
    read_file = lambda file_name: (file_name, open(mustache_dir / file_name, "r").read())
    strip_file_name = lambda x: (x[0].rpartition('.')[0], x[1])
26
    wrap_in_tag = lambda x: "<script type='text/template' id='{0}'>{1}</script>".format(x[0], x[1])
27 28 29 30

    file_contents = map(read_file, filter(valid_file_name, os.listdir(mustache_dir)))
    return '\n'.join(map(wrap_in_tag, map(strip_file_name, file_contents)))

31
def render_content(content, additional_context={}):
Ibrahim Awwal committed
32

Rocky Duan committed
33
    context = {
34
        'content': extend_content(content),
35
        content['type']: True,
Rocky Duan committed
36
    }
Arjun Singh committed
37 38 39 40 41 42 43
    if cc_settings.MAX_COMMENT_DEPTH is not None:
        if content['type'] == 'thread':
            if cc_settings.MAX_COMMENT_DEPTH < 0:
                context['max_depth'] = True
        elif content['type'] == 'comment':
            if cc_settings.MAX_COMMENT_DEPTH <= content['depth']:
                context['max_depth'] = True
44 45 46
    context = merge_dict(context, additional_context)
    partial_mustache_helpers = {k: partial(v, content) for k, v in mustache_helpers.items()}
    context = merge_dict(context, partial_mustache_helpers)
47
    return render_mustache('discussion/mustache/_content.mustache', context)