Hasty Briefsbeta

Bilingual

FastHTML Best Practices

a year ago
  • #Best Practices
  • #FastHTML
  • #Web Development
  • FastHTML applications differ from those using FastAPI/react, Django, etc., and follow the fast.ai philosophy: remove ceremony, leverage smart defaults, and write concise, clear code.
  • Database table creation is simplified with FastLite's idempotent `create()` method, using dataclass-style definitions for cleaner, more Pythonic code.
  • Route naming conventions allow function names to define routes, with `index` mapping to `/` and other function names becoming routes automatically.
  • Query parameters are preferred over path parameters in FastHTML for more idiomatic URLs and avoiding parameter name duplication.
  • Leverage return values from `insert()` and `update()` methods for functional chaining, simplifying code.
  • Use `.to()` method for URL generation, providing type safety and refactoring-friendly code.
  • PicoCSS is included by default in FastHTML, allowing for automatic styling of semantic HTML elements without custom CSS.
  • Smart defaults in FastHTML include automatic wrapping of content in `Container` by `Titled` and internal handling of `if __name__ == "__main__":` by `serve()`.
  • FastHTML components accept iterables directly, eliminating the need to unpack with `*`.
  • Functional patterns like `map()` are cleaner for simple transformations, especially with FastHTML's iterable handling.
  • Minimal code practices include skipping comments for self-documenting code, not returning empty strings, and using single lines for single ideas.
  • Use POST for all mutations in FastHTML, as it handles only GET and POST by default, making it more idiomatic and simpler.
  • Modern HTMX event syntax in FastHTML converts underscores to hyphens, simplifying event handling with `hx-on__event` syntax.