theme.py 2.2 KB

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