templates.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. """Templates to use in the pynecone compiler."""
  2. from jinja2 import Environment, FileSystemLoader, Template
  3. from pynecone import constants
  4. from pynecone.utils import path_ops
  5. from pynecone.utils.format import json_dumps
  6. class PyneconeJinjaEnvironment(Environment):
  7. """The template class for jinja environment."""
  8. def __init__(self) -> None:
  9. """Set default environment."""
  10. extensions = ["jinja2.ext.debug"]
  11. super().__init__(
  12. extensions=extensions,
  13. trim_blocks=True,
  14. lstrip_blocks=True,
  15. )
  16. self.filters["json_dumps"] = json_dumps
  17. self.filters["react_setter"] = lambda state: f"set{state.capitalize()}"
  18. self.loader = FileSystemLoader(constants.JINJA_TEMPLATE_DIR)
  19. self.globals["const"] = {
  20. "socket": constants.SOCKET,
  21. "result": constants.RESULT,
  22. "router": constants.ROUTER,
  23. "event_endpoint": constants.Endpoint.EVENT.name,
  24. "events": constants.EVENTS,
  25. "state": constants.STATE,
  26. "processing": constants.PROCESSING,
  27. "initial_result": {
  28. constants.STATE: None,
  29. constants.EVENTS: [],
  30. constants.PROCESSING: False,
  31. },
  32. "color_mode": constants.COLOR_MODE,
  33. "toggle_color_mode": constants.TOGGLE_COLOR_MODE,
  34. "use_color_mode": constants.USE_COLOR_MODE,
  35. "hydrate": constants.HYDRATE,
  36. "db_url": constants.DB_URL,
  37. }
  38. def get_template(name: str) -> Template:
  39. """Get render function that work with a template.
  40. Args:
  41. name: The template name. "/" is used as the path separator.
  42. Returns:
  43. A render function.
  44. """
  45. return PyneconeJinjaEnvironment().get_template(name=name)
  46. # Template for the Pynecone config file.
  47. PCCONFIG = get_template("app/pcconfig.py.jinja2")
  48. # Code to render a NextJS Document root.
  49. DOCUMENT_ROOT = get_template("web/pages/_document.js.jinja2")
  50. # Template for the theme file.
  51. THEME = get_template("web/utils/theme.js.jinja2")
  52. # Code to render a single NextJS page.
  53. PAGE = get_template("web/pages/index.js.jinja2")
  54. # Code to render the custom components page.
  55. COMPONENTS = get_template("web/pages/custom_component.js.jinja2")
  56. # Sitemap config file.
  57. SITEMAP_CONFIG = "module.exports = {config}".format
  58. FULL_CONTROL = path_ops.join(
  59. [
  60. "{{setState(prev => ({{",
  61. "...prev,{state_name}: {arg}",
  62. "}}), ",
  63. "()=>Event([{chain}])",
  64. ")}}",
  65. ]
  66. ).format