Skip to content

Support for "for" attribute #3

Description

@frankie567

Hey 👋

I'm starting to use Tagflow for an internal tool @polarsource :)

Current behavior

While starting to write some HTML, I noticed there was no specific handling for the for keyword argument, as there is for class, which is required since for is a reserved keyword in Python.

The for attribute is particularly useful in forms to link label with input, e.g.

<label for="my-field">Email</label>
<input type="email" id="my-field" />

Intuitively, I tried to write it like this:

with tag.label(for_="my-field"):
    text("Email")

But it's actually rendered directly as for_.

Workaround

I can workaround this by unpacking a dictionary:

with tag.label(**{"for": "my-field"}):
    text("Email")

But that's a bit verbose 😄 It would be nice to have a special syntax like for_ to handle this case.

Notes

I guess the magic happens here:

def attr_name_to_xml(name: str) -> str:
"""
Convert Pythonic attribute names to valid HTML/XML attribute names.
If 'classes' or 'class_' is passed in, that maps to the 'class' attribute.
Otherwise, replace underscores between word characters with hyphens.
"""
if name == "classes" or name == "class_":
return "class"
return re.sub(r"(\w)_(\w)", r"\1-\2", name)

If you want, I would be happy to submit a PR for it :)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions