jimbaker / tagstr

This repo contains an issue tracker, examples, and early work related to PEP 999: Tag Strings
51 stars 6 forks source link

add htmldom.py + a bit of the html tutorial #12

Closed rmorshea closed 1 year ago

rmorshea commented 2 years ago

This includes an intro for html tags (up until I got distracted making htmldom.py).

htmldom.py implements a more complete version of the html tag we discussed in person - it supports attribute expansion along with interpolation of tags and attributes and does so while still relying on html.parser. For example, the following:

color = "blue"
attrs = {"style": {"font-size": "bold", "font-family": "mono"}}
dom = html"<a {attrs} color=dark{color} >{html'<h{i}/>' for i in range(1, 4)}</a>".render(indent=2)
print(dom)

Produces:

<a style="font-size:bold; font-family:mono" color="darkblue">
  <h1></h1>
  <h2></h2>
  <h3></h3>
</a>

My hope was that if I could implement this more fully featured html tag using html.parser it would remain approachable while also being more compelling. However, having implemented it now, I'm unsure of how it will pan out given the added complexity.

rmorshea commented 2 years ago

htmldom.py includes some editorializing. Specifically, it disallows attribute name interpolation. My reasoning here is that if you truly need to interpolate the name of an HTML attribute, you could just as easily form the name in a dictionary, and then use attribute expansion:

attrs = {f"my{attr}": True}
html"<a {attrs} />"

At present, I'm unsure if JSX has come to the same decision.

rmorshea commented 2 years ago

Thanks for the feedback. I'll make those changes and see if I can break down the program in a reasonable way for the tutorial.

rmorshea commented 2 years ago

I've managed to simplify htmldom.py even more. I realized that I could store all the expression values in a list and interleave them with the HTML as it was parsed. This removes the need for any hackery with string.Template and will make things much easier to explain in the tutorial (which I started getting to the meat of).

rmorshea commented 1 year ago

Definitely agree. As you said, it would be better to introduce tag string examples first and then present a comparison with Jinja. Also, the intro "Applications in templating" section does not cleanly lead into the meat of the tutorial in the following "Writing an html tag" section. I'll work on follow-up edits. Thankfully I think nearly all the content is there, so making these improvements should be much quicker.