helpers.py 1.98 KB
Newer Older
1
from django.conf import settings
2
from .mustache_helpers import mustache_helpers
3 4
from functools import partial

5
from .utils import extend_content, merge_dict, render_mustache
Arjun Singh committed
6
import django_comment_client.settings as cc_settings
7

8
import pystache_custom as pystache
Rocky Duan committed
9
import urllib
10
import os
Rocky Duan committed
11

12 13 14
# This method is used to pluralize the words "discussion" and "comment"
# when referring to how many discussion threads or comments the user
# has contributed to.
Calen Pennington committed
15 16


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

22
# TODO there should be a better way to handle this
Calen Pennington committed
23 24


25
def include_mustache_templates():
26
    mustache_dir = settings.PROJECT_ROOT / 'templates' / 'discussion' / 'mustache'
27 28 29
    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])
30
    wrap_in_tag = lambda x: "<script type='text/template' id='{0}'>{1}</script>".format(x[0], x[1])
31 32 33 34

    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)))

Calen Pennington committed
35

36
def render_content(content, additional_context={}):
Ibrahim Awwal committed
37

Rocky Duan committed
38
    context = {
39
        'content': extend_content(content),
40
        content['type']: True,
Rocky Duan committed
41
    }
Arjun Singh committed
42 43 44 45 46 47 48
    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
49 50 51
    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)
52
    return render_mustache('discussion/mustache/_content.mustache', context)