Plain is headed towards 1.0! Subscribe for development updates →

plain.elements

Installation

# settings.py
INSTALLED_PACKAGES = [
    # ...
    "plain.elements",
]
  1import os
  2import re
  3
  4from jinja2 import nodes
  5from jinja2.ext import Extension
  6
  7from plain.runtime import settings
  8from plain.templates import register_template_extension
  9from plain.utils.functional import cached_property
 10
 11
 12@register_template_extension
 13class ElementsExtension(Extension):
 14    def preprocess(self, source, name, filename=None):
 15        if os.path.splitext(filename)[1] in [".html", ".md"]:
 16            return self.replace_template_element_tags(source)
 17        return source
 18
 19    @cached_property
 20    def template_elements(self):
 21        elements = []
 22
 23        loader = self.environment.loader
 24
 25        for searchpath in loader.searchpath:
 26            elements_dir = os.path.join(searchpath, "elements")
 27            if os.path.isdir(elements_dir):
 28                for root, dirs, files in os.walk(elements_dir):
 29                    for file in files:
 30                        relative_path = os.path.relpath(
 31                            os.path.join(root, file), elements_dir
 32                        )
 33                        # Replace slashes with .
 34                        element_name = os.path.splitext(relative_path)[0].replace(
 35                            os.sep, "."
 36                        )
 37                        elements.append(
 38                            {
 39                                "path": relative_path,
 40                                "html_name": element_name,  # Uses . syntax
 41                                "tag_name": element_name.replace(
 42                                    ".", "_"
 43                                ),  # Uses _ syntax
 44                            }
 45                        )
 46
 47        for element in elements:
 48            element_name = element["html_name"]
 49            jinja_tag_name = element["tag_name"]
 50            element_relative_path = element["path"]
 51
 52            class ElementExtension(Extension):
 53                def parse(self, parser):
 54                    lineno = next(parser.stream).lineno
 55                    args = [
 56                        nodes.DerivedContextReference(),
 57                    ]
 58                    kwargs = []
 59                    while parser.stream.current.type != "block_end":
 60                        if parser.stream.current.type == "name":
 61                            key = parser.stream.current.value
 62                            parser.stream.skip()
 63                            parser.stream.expect("assign")
 64                            value = parser.parse_expression()
 65                            kwargs.append(nodes.Keyword(key, value))
 66
 67                    body = parser.parse_statements(
 68                        ["name:end" + self.jinja_tag_name], drop_needle=True
 69                    )
 70
 71                    call = self.call_method(
 72                        "_render", args=args, kwargs=kwargs, lineno=lineno
 73                    )
 74
 75                    self.source_ref = f"{parser.name}:{lineno}"
 76
 77                    return nodes.CallBlock(call, [], [], body).set_lineno(lineno)
 78
 79                def _render(self, context, **kwargs):
 80                    template = self.environment.get_template(self.template_name)
 81                    rendered = template.render({**context, **kwargs})
 82
 83                    if settings.DEBUG:
 84                        # Add an HTML comment in dev to help identify elements in output
 85                        return f"<!-- <{self.html_name}>\n{self.source_ref} -->\n{rendered}\n<!-- </{self.html_name}> -->"
 86                    else:
 87                        return rendered
 88
 89            # Create a new class on the fly
 90            NamedElementExtension = type(
 91                f"PlainElement.{element_name}",
 92                (ElementExtension,),
 93                {
 94                    "tags": {jinja_tag_name, f"end{jinja_tag_name}"},
 95                    "template_name": f"elements/{element_relative_path}",
 96                    "jinja_tag_name": jinja_tag_name,
 97                    "html_name": element_name,
 98                },
 99            )
100            self.environment.add_extension(NamedElementExtension)
101
102        return elements
103
104    def replace_template_element_tags(self, contents: str):
105        def replace_quoted_braces(s) -> str:
106            """
107            We're converting to tag syntax, but it's very natural to write
108            <Label for="{{ thing }}"> vs <Label for=thing>
109            so we just convert the first to the second automatically.
110            """
111            return re.sub(r"(?<=\"{{)(.+)(?=}}\")", r"\1", s)
112
113        for element in self.template_elements:
114            element_name = element["html_name"]
115            jinja_tag_name = element["tag_name"]
116
117            closing_pattern = re.compile(
118                rf"<{element_name}(\s+[\s\S]*?)?>([\s\S]*?)</{element_name}>"
119            )
120            self_closing_pattern = re.compile(rf"<{element_name}(\s+[\s\S]*?)?/>")
121
122            def closing_cb(match: re.Match) -> str:
123                if f"<{element_name}" in match.group(2):
124                    raise ValueError(
125                        f"Element {element_name} cannot be nested in itself"
126                    )
127
128                attrs_str = match.group(1) or ""
129                inner = match.group(2)
130
131                attrs_str = replace_quoted_braces(attrs_str)
132                return f"{{% {jinja_tag_name} {attrs_str} %}}{inner}{{% end{jinja_tag_name} %}}"
133
134            contents = closing_pattern.sub(closing_cb, contents)
135
136            def self_closing_cb(match: re.Match) -> str:
137                attrs_str = match.group(1) or ""
138
139                attrs_str = replace_quoted_braces(attrs_str)
140                return (
141                    f"{{% {jinja_tag_name} {attrs_str} %}}{{% end{jinja_tag_name} %}}"
142                )
143
144            contents = self_closing_pattern.sub(self_closing_cb, contents)
145
146        if match := re.search(r"<[A-Z].*>", contents):
147            raise ValueError(
148                f"Found unmatched uppercase tag in template: {match.group(0)}"
149            )
150
151        if match := re.search(r"<[a-z_]+\.[A-Z]+.*>", contents):
152            raise ValueError(
153                f"Found unmatched nested tag in template: {match.group(0)}"
154            )
155
156        return contents