Skip to content

Leave pre-formatted kwarg attributes as-is#118

Closed
gazpachoking wants to merge 1 commit intopelme:mainfrom
gazpachoking:preformatted-kwarg-attributes
Closed

Leave pre-formatted kwarg attributes as-is#118
gazpachoking wants to merge 1 commit intopelme:mainfrom
gazpachoking:preformatted-kwarg-attributes

Conversation

@gazpachoking
Copy link
Copy Markdown
Contributor

Prevents the underscore replacement in attribute names if the name already has a dash, e.g.:

div(**{'data-my-weird_attribute': value})
<div data-my-weird_attribute="value"></div>

Previously the underscore would have been written as a dash.

Motivation is to be able to use datastar attributes, which have both dashes and underscores.
Since the only way to get dashes in the kwargs dict is to unpack them from a dict on the calling side this feels pretty safe. Similar to how attributes are not rewritten when they are passed in a dict as the first argument.

@pelme
Copy link
Copy Markdown
Owner

pelme commented May 24, 2025

did you consider just passing the dict directly? then it is used directly as-is:

>>> print(div({"data-foo__bar": "value"}))
<div data-foo__bar="value"></div>

@gazpachoking
Copy link
Copy Markdown
Contributor Author

gazpachoking commented May 24, 2025

This is related to the datastar attribute helper again, and it was a workaround for not being able to pass in more than one dict of attributes. I was looking at how fasthtml does it (like this, with unpacked kwargs) and I thought leaving already formatted attributes would be 'the right thing' and decided to raise this PR. Either this or #117 would solve the issue of not being able to use multiple dicts at the moment. I'd probably use #117 way if they both went in, but this PR seemed like it'd also be the intended behavior in any case.

@gazpachoking
Copy link
Copy Markdown
Contributor Author

In fact perhaps the check should be not name.isidentifier() so it applies to anything that couldn't have come from a kwarg directly.

@gazpachoking
Copy link
Copy Markdown
Contributor Author

Actually, I think I changed my mind on this one. Since we can't be sure which kwargs came from an unpacked dict and which were actual keyword arguments it's not a safe way to pass preformatted attributes (i.e. div(**{'underscore_attr': 'blah'}) would still be rewritten.) #117 is a nicer solution to my actual issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants