Last active
November 29, 2023 20:19
-
-
Save bion/a1c7d3d4128e7a66d9d4b79baeb6fee9 to your computer and use it in GitHub Desktop.
HTML TO J2HTML WHEN WILL THE MADNESS STOP?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env python3 | |
from html.parser import HTMLParser | |
import io | |
import sys | |
class J2HtmlGenerator(HTMLParser): | |
def __init__(self): | |
HTMLParser.__init__(self) | |
self.output = io.StringIO() | |
self.attr_stack = [] | |
self.last_out_token = "" | |
def _append_output(self, out): | |
self.output.write(out) | |
self.last_out_token = out | |
def _prepend_comma_if_needed(self): | |
if self.last_out_token.endswith(")"): | |
self._append_output(", ") | |
def handle_starttag(self, tag, attrs): | |
self.attr_stack.append(attrs) | |
self._prepend_comma_if_needed() | |
self._append_output(tag + "(") | |
def handle_endtag(self, tag): | |
self._append_output(")") | |
attrs = self.attr_stack.pop() | |
if not attrs: | |
return | |
for attr_pair in attrs: | |
name = attr_pair[0] | |
val = attr_pair[1] | |
if name == "class": | |
self._append_output('.withClass("' + val + '")') | |
elif name == "id": | |
self._append_output('.withId("' + val + '")') | |
elif name == "href": | |
self._append_output('.withHref("' + val + '")') | |
elif name == "name": | |
self._append_output('.withName("' + val + '")') | |
elif name == "accept": | |
self._append_output('.withAccept("' + val + '")') | |
elif name == "src": | |
self._append_output('.withSrc("' + val + '")') | |
elif name == "alt": | |
self._append_output('.withAlt("' + val + '")') | |
elif name == "action": | |
self._append_output('.withAction("' + val + '")') | |
elif name == "method": | |
self._append_output('.withMethod("' + val + '")') | |
elif name == "value": | |
self._append_output('.withValue("' + val + '")') | |
elif name == "type": | |
self._append_output('.withType("' + val + '")') | |
else: | |
self._append_output('.attr("' + name + '", "' + val + '")') | |
def handle_data(self, data): | |
data = data.strip() | |
if data: | |
self._prepend_comma_if_needed() | |
self._append_output('text("' + data + '")') | |
def result(self): | |
return self.output.getvalue() | |
generator = J2HtmlGenerator() | |
generator.feed(sys.stdin.read()) | |
print(generator.result() + ";") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment