sanic-org / html5tagger

Create HTML documents from Python
The Unlicense
29 stars 4 forks source link

Turn a Builder into a tree, and allow for pretty printing HTML #10

Open ahopkins opened 1 year ago

ahopkins commented 1 year ago

The main purpose of this PR is to enable functionality to output HTML with line breaks and indentation for easily viewing and debugging.

tree = HTMLSyntaxTree.create(doc)
tree.display_tree()  # Prints a representation of the tree
print(tree.to_html())
print(tree.to_html(pretty=True))
Tronic commented 1 year ago

Turning Builder itself into a tree would turn html5tagger into a DOM, which is contrary to its core design principle: being based on HTML5 rather than XHTML it doesn't need to know where elements end and thus cannot form a tree. There are a few other similar DSL builders but they all depend on a strict tree structure in document construction.

This PR instead implements a parser, that could almost just as well be stand-alone, not needing Builder. We've had a background discussion on this in more detail, where it was noted that it currently does depend on how Builder splits HTML5 snippets to separate strings but that it couldn't really rely on that given an optimization where adjacent strs are concatenated for faster rendering (using templates). There might not be existing functional HTML5 parsers / renderers that can function with no end tags. It was noted that the most popular option BeautifulSoup has many issues with this.

An alternative (not suggested) option would be to modify Builder itself to construct a tree, where the DSL and the HTML output would still work without end tags. This makes it different from DOM in that the module internally knows where the elements end by HTML5 specification.

Leaving open for now, for extra discussion on which if any direction to take. A parser submodule seems easy enough but I would prefer it to work on plain document str, which would make it more useful in general use (and not interfere with that planned optimization).