pelme / htpy

Generate HTML in Python
http://htpy.dev
MIT License
261 stars 11 forks source link

Handle "False" child elements #40

Closed ggranger closed 3 months ago

ggranger commented 4 months ago

I'm submitting this tiny change to improve conditional rendering.

Currently, only "None" nodes are skipped. This is useful to implement conditional rendering based on a nullable variable, as shown in the docs.

print(div[error and b[error]])

Unfortunately, most conditional rendering often relies on a boolean condition, and in this case, you can't do print(div[has_error and b[error_msg]]) because you will get an error ValueError: False is not a valid child element

The current best way to have conditional rendering based on a boolean is to adopt the ternary operator print(div[b[error_msg] if has_error else None]).

Drawbacks are:

The suggested change aims to allow the print(div[has_error and b[error_msg]]) syntax for boolean conditional rendering.

pelme commented 4 months ago

Hi @ggranger, thanks for bringing this up. There have been a bit of back and forth on this. I agree that this is nice. I did not previously know how to deal with typing and True. I looked into what React does. React just ignores True. So.. having a way to deal with True which makes it possible to add bool to the Node type. I created #41 with updated docs+types+tests, please have a look at it!

ggranger commented 4 months ago

Thanks for that and congrats for adding the True value as well as part of the ignored values which is helpful to handle the or construct in addition to the and one (I left a comment on your PR regarding that part).