theme.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. from django.conf import settings
  2. from coffin.shortcuts import render_to_response
  3. from coffin.template import dict_from_django_context
  4. from coffin.template.loader import get_template, select_template, render_to_string
  5. '''Monkeypatch Django to mimic Jinja2 behaviour'''
  6. from django.utils import safestring
  7. if not hasattr(safestring, '__html__'):
  8. safestring.SafeString.__html__ = lambda self: str(self)
  9. safestring.SafeUnicode.__html__ = lambda self: unicode(self)
  10. class Theme(object):
  11. def __init__(self, theme):
  12. self.set_theme(theme);
  13. def set_theme(self, theme):
  14. if theme not in settings.INSTALLED_THEMES:
  15. raise ValueError('"%s" is not correct theme name.' % theme)
  16. if theme[0] == '_':
  17. raise ValueError('"%s" is a template package, not a theme.' % theme[1:])
  18. self._theme = theme;
  19. def reset_theme(self):
  20. self._theme = settings.INSTALLED_THEMES[0]
  21. def get_theme(self):
  22. return self._theme
  23. def prefix_templates(self, templates):
  24. if isinstance(templates, str):
  25. return ('%s/%s' % (self._theme, templates), templates)
  26. else:
  27. prefixed = []
  28. for template in templates:
  29. prefixed.append('%s/%s' % (self._theme, template))
  30. prefixed += templates
  31. return prefixed
  32. def render_to_string(self, templates, *args, **kwargs):
  33. templates = self.prefix_templates(templates)
  34. return render_to_string(templates, *args, **kwargs)
  35. def render_to_response(self, templates, *args, **kwargs):
  36. templates = self.prefix_templates(templates)
  37. return render_to_response(templates, *args, **kwargs)
  38. def macro(self, templates, macro, dictionary={}, context_instance=None):
  39. templates = self.prefix_templates(templates)
  40. template = select_template(templates)
  41. if context_instance:
  42. context_instance.update(dictionary)
  43. else:
  44. context_instance = dictionary
  45. context_instance = dict_from_django_context(context_instance)
  46. _macro = getattr(template.make_module(context_instance), macro)
  47. return unicode(_macro()).strip()
  48. def get_email_templates(self, template, contex={}):
  49. email_type_plain = '_email/%s.txt' % template
  50. email_type_html = '_email/%s.html' % template
  51. return (
  52. select_template(('%s/%s' % (self._theme, email_type_plain[1:]), email_type_plain)),
  53. select_template(('%s/%s' % (self._theme, email_type_html[1:]), email_type_html)),
  54. )