templates.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. "final": constants.FINAL,
  27. "processing": constants.PROCESSING,
  28. "initial_result": {
  29. constants.STATE: None,
  30. constants.EVENTS: [],
  31. constants.FINAL: True,
  32. constants.PROCESSING: False,
  33. },
  34. "color_mode": constants.COLOR_MODE,
  35. "toggle_color_mode": constants.TOGGLE_COLOR_MODE,
  36. "use_color_mode": constants.USE_COLOR_MODE,
  37. "hydrate": constants.HYDRATE,
  38. "db_url": constants.DB_URL,
  39. }
  40. def get_template(name: str) -> Template:
  41. """Get render function that work with a template.
  42. Args:
  43. name: The template name. "/" is used as the path separator.
  44. Returns:
  45. A render function.
  46. """
  47. return PyneconeJinjaEnvironment().get_template(name=name)
  48. # Template for the Pynecone config file.
  49. PCCONFIG = get_template("app/pcconfig.py.jinja2")
  50. # Code to render a NextJS Document root.
  51. DOCUMENT_ROOT = get_template("web/pages/_document.js.jinja2")
  52. # Template for the theme file.
  53. THEME = get_template("web/utils/theme.js.jinja2")
  54. # Template for Tailwind config.
  55. TAILWIND_CONFIG = get_template("web/tailwind.config.js.jinja2")
  56. # Code to render a single NextJS page.
  57. PAGE = get_template("web/pages/index.js.jinja2")
  58. # Code to render the custom components page.
  59. COMPONENTS = get_template("web/pages/custom_component.js.jinja2")
  60. # Sitemap config file.
  61. SITEMAP_CONFIG = "module.exports = {config}".format
  62. FULL_CONTROL = path_ops.join(
  63. [
  64. "{{setState(prev => ({{",
  65. "...prev,{state_name}: {arg}",
  66. "}}), ",
  67. "()=>Event([{chain}])",
  68. ")}}",
  69. ]
  70. ).format