You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

loader.py 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. from . import engines
  2. from .exceptions import TemplateDoesNotExist
  3. def get_template(template_name, using=None):
  4. """
  5. Load and return a template for the given name.
  6. Raise TemplateDoesNotExist if no such template exists.
  7. """
  8. chain = []
  9. engines = _engine_list(using)
  10. for engine in engines:
  11. try:
  12. return engine.get_template(template_name)
  13. except TemplateDoesNotExist as e:
  14. chain.append(e)
  15. raise TemplateDoesNotExist(template_name, chain=chain)
  16. def select_template(template_name_list, using=None):
  17. """
  18. Load and return a template for one of the given names.
  19. Try names in order and return the first template found.
  20. Raise TemplateDoesNotExist if no such template exists.
  21. """
  22. if isinstance(template_name_list, str):
  23. raise TypeError(
  24. 'select_template() takes an iterable of template names but got a '
  25. 'string: %r. Use get_template() if you want to load a single '
  26. 'template by name.' % template_name_list
  27. )
  28. chain = []
  29. engines = _engine_list(using)
  30. for template_name in template_name_list:
  31. for engine in engines:
  32. try:
  33. return engine.get_template(template_name)
  34. except TemplateDoesNotExist as e:
  35. chain.append(e)
  36. if template_name_list:
  37. raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain)
  38. else:
  39. raise TemplateDoesNotExist("No template names provided")
  40. def render_to_string(template_name, context=None, request=None, using=None):
  41. """
  42. Load a template and render it with a context. Return a string.
  43. template_name may be a string or a list of strings.
  44. """
  45. if isinstance(template_name, (list, tuple)):
  46. template = select_template(template_name, using=using)
  47. else:
  48. template = get_template(template_name, using=using)
  49. return template.render(context, request)
  50. def _engine_list(using=None):
  51. return engines.all() if using is None else [engines[using]]