Preemptively parsing t-string templates #63
Replies: 2 comments 5 replies
-
|
Hi @ianjosephwilson -- thanks for playing with The good news is that The first time you call We don't currently have tools for static analysis of your t-string contents; right now, the only way to find out if you typed in the HTML correctly is to call The straightforward way to write your code would be: from tdom import html, Node
def html_selected_nav_item(label: str) -> Node:
return html(t"<li><b>{label}</b></li>")
def html_nav_item(label: str, href: str) -> Node:
return html(t"<li><a href={href}>{label}</a></li>")
def html_nav(items: list[tuple[str, str]], selected_href: str | None = None) -> Node:
nav_items = [
html_selected_nav_item(label)
if href == selected_href
else html_nav_item(label, href)
for label, href in items
]
return html(t"<ul>{nav_items}</ul>")
def html_header(title: str, nav_ul: Node) -> Node:
return html(t"""
<div class="heading-container"><h1>{title}</h1>
<div class="nav">{nav_ul}</div>
</div>
""")
def main():
node = html_header(
"My Cool Site",
html_nav(
[("Home", "/"), ("About", "/about"), ("News", "/news")],
selected_href="/news",
),
)
print(str(node))
if __name__ == "__main__":
main()Hope this makes sense! If there's something else you're looking to do not covered here, please let me know. |
Beta Was this translation helpful? Give feedback.
-
|
Of course, you might not want to wait that long for static tools to catch up. You could write a tool that recursed your code base, using I should also add:
|
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
In this example I use a decorator to just preemptively run the t-strings through the
html()function because it keeps that call close to the template function itself but it could also just be an explicit function that calls all the module functions likedef run_templates()or something that could be run from somewhere else. This all seems like pretty weird hacks. Is there anything more pre-preemptive other than just waiting for the t-string to be executed during some run-time rendering of the application? Or could the AST be used somehow to just pull out ALL t-strings of functions starting withhtml_and then pre-parse them to check for correctness and cache the parsed structure?Thanks.
Example
Beta Was this translation helpful? Give feedback.
All reactions