No Description
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.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #-*- coding: utf-8 -*-
  2. import jinja2
  3. import settings
  4. from .api import api_lodel_templates
  5. from .exceptions import NotAllowedCustomAPIKeyError
  6. class TemplateLoader(object):
  7. __reserved_template_keys = ['lodel']
  8. ## @brief Initializes a template loader
  9. #
  10. # @param search_path str : the base path from which the templates are searched. To use absolute paths, you can set
  11. # it to the root "/". By default, it will be the root of the project, defined in the
  12. # settings of the application
  13. # @param follow_links bool : indicates whether or not to follow the symbolic links (default: True)
  14. def __init__(self, search_path=settings.base_path, follow_links=True):
  15. self.search_path = search_path
  16. self.follow_links = follow_links
  17. ## @brief Renders a HTML content of a template
  18. #
  19. # @param template_file str : path to the template file (starting from the base path used to instanciate the
  20. # TemplateLoader)
  21. # @param template_vars dict : parameters to be used in the template
  22. # @param template_extra list : list of tuples indicating the custom modules to import in the template (default: None).
  23. # The modules are given as tuples with the format : ('name_to_use_in_the_template', module)
  24. #
  25. # @return str. String containing the HTML output of the processed templated
  26. def render_to_html(self, template_file, template_vars={}, template_extra=None):
  27. loader = jinja2.FileSystemLoader(searchpath=self.search_path, followlinks=self.follow_links)
  28. environment = jinja2.Environment(loader=loader)
  29. template = environment.get_template(template_file)
  30. # Lodel2 default api is loaded
  31. template.globals['lodel'] = api_lodel_templates
  32. # Extra modules are loaded
  33. if template_extra is not None:
  34. for extra in template_extra:
  35. if not self.__is_allowed_template_key(extra[0]):
  36. raise NotAllowedCustomAPIKeyError("The name 'lodel' is a reserved one for the loaded APIs in templates")
  37. template.globals[extra[0]] = extra[1]
  38. return template.render(template_vars)
  39. ## @brief Checks if the key used for the template is allowed
  40. #
  41. # @param key str
  42. # @return bool
  43. def __is_allowed_template_key(self, key):
  44. return False if key in self.__class__.__reserved_template_keys else True