leforestier / yattag

Python library to generate HTML or XML in a readable, concise and pythonic way.
332 stars 31 forks source link

label tag cannot be generated as `for` is a python keyword #74

Closed rajeshnair closed 2 years ago

rajeshnair commented 2 years ago

I need to generate html label keyword which uses for as attribute

<input id="rbtn1" name="group1" type="radio" checked>
  <label for="rbtn1">Label 1</label>

  <input id="rbtn2" name="group1" type="radio">
  <label for="rbtn2">Label 2</label>

But this cannot be done using yattag as for is also a python keyword. Can simply be handled as class keyword is handled

from yattag import Doc, indent
doc, tag, text = Doc().tagtext()

with tag('html'):
        with tag('head'):
            doc.stag('script', src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js')
        with tag('body'):
            doc.stag("input", id="r1", name="group1", value="r1")
            with tag('label', for="r1"):
                text("option 1")
            doc.stag("input", id="r2", name="group1", value="r2")
            with tag('label', for="r2"):
                text("option 1")
            doc.stag("input", id="r3", name="group1", value="r3")
            with tag('label', for="r3"):
                text("option 1")

print(indent(doc.getvalue()))

gives

  File "test.py", line 9
    with tag('label', for="r1"):
leforestier commented 2 years ago

You can use (key, value) pairs. Like this:

with tag('label', ('for', 'r1')):
    ...
rajeshnair commented 2 years ago

Thanks ! That works!

But I did not see that documented anywhere. Also should not the same scenario be used to handle the class keyword. Having two different mechanism for handling python keywords is confusing for users

leforestier commented 2 years ago

The use of (key, value) pairs to pass html attributes is mentionned on https://www.yattag.org As for the class/klass trick, if I had to write that library from scratch, I wouldn't include it. But I can't remove it since a lot of people rely on it now.