render.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import pathlib
  2. from typing import List
  3. from ray.util.annotations import DeveloperAPI
  4. @DeveloperAPI
  5. class Template:
  6. """Class which provides basic HTML templating."""
  7. def __init__(self, file: str):
  8. with open(pathlib.Path(__file__).parent / "templates" / file, "r") as f:
  9. self.template = f.read()
  10. def render(self, **kwargs) -> str:
  11. """Render an HTML template with the given data.
  12. This is done by replacing instances of `{{ key }}` with `value`
  13. from the keyword arguments.
  14. Returns:
  15. HTML template with the keys of the kwargs replaced with corresponding
  16. values.
  17. """
  18. rendered = self.template
  19. for key, value in kwargs.items():
  20. if isinstance(value, List):
  21. value = "".join(value)
  22. rendered = rendered.replace("{{ " + key + " }}", value if value else "")
  23. return rendered
  24. @staticmethod
  25. def list_templates() -> List[pathlib.Path]:
  26. """List the available HTML templates.
  27. Returns:
  28. A list of files with .html.j2 extensions inside ../templates/
  29. """
  30. return (pathlib.Path(__file__).parent / "templates").glob("*.html.j2")