pythonhtmlfasthtml

How to output an empty attribute in FastHTML?


In FastHTML I want to output <option value="">(select)</option> for a FastTag component. However, this code…

from fasthtml.core import to_xml
from fasthtml.components import Option
opt = Option("(select)", value="")
print(to_xml(opt))

…results in <option>(select)</option>. This causes the browser to use the value (select) when this option is chosen. I don't want to use 0 or - or something else, I want a truly empty value. How do I get it?


Solution

  • In FastHTML you can pass a keyword argument with a value of True to get a bare attribute created:

    Option("(select)", value=True, selected=True)
    #=> <option value selected>(select)</option>
    

    This is treated the same as an empty value by the browser.