Here are the docs for FastHTML: <project title="FastHTML" summary='FastHTML is a python…
- User
Here are the docs for FastHTML: Things to remember when writing FastHTML apps:
- Although parts of its API are inspired by FastAPI, it is not compatible with FastAPI syntax and is not targeted at creating API services
- FastHTML includes support for Pico CSS and the fastlite sqlite library, although using both are optional; sqlalchemy can be used directly or via the fastsql library, and any CSS framework can be used. Support for the Surreal and css-scope-inline libraries are also included, but both are optional
- FastHTML is compatible with JS-native web components and any vanilla JS library, but not with React, Vue, or Svelte
- Use
serve()for running uvicorn (if __name__ == "__main__"is not needed since it's automatic) - When a title is needed with a response, use
Titled; note that that already wraps children inContainer, and already includes both the meta title as well as the H1 element.# Web Devs Quickstart
Installation
pip install python-fasthtmlA Minimal Application
A minimal FastHTML application looks something like this:
main.py
from fasthtml.common import * app, rt = fast_app() @rt("/") def get(): return Titled("FastHTML", P("Let's do this!")) serve()Line 1
We import what we need for rapid development! A carefully-curated set of FastHTML functions and other Python objects is brought into our global namespace for convenience.Line 3
We instantiate a FastHTML app with thefast_app()utility function. This provides a number of really useful defaults that we’ll take advantage of later in the tutorial.Line 5
We use thert()decorator to tell FastHTML what to return when a user visits/in their browser.Line 6
We connect this route to HTTP GET requests by defining a view function calledget().Line 7
A tree of Python function calls that return all the HTML required to write a properly formed web page. You’ll soon see the power of this approach.Line 9
Theserve()utility configures and runs FastHTML using a library calleduvicorn.Run the code:
python main.pyThe terminal will look like this:
INFO: Uvicorn running on http://0.0.0.0:5001 (Press CTRL+C to quit) INFO: Started reloader process [58058] using WatchFiles INFO: Started server process [58060] INFO: Waiting for application startup. INFO: Application startup complete.Confirm FastHTML is running by opening your web browser to 127.0.0.1:5001. You should see something like the image below:
[image]
Note
While some linters and developers will complain about the wildcard import, it is by design here and perfectly safe. FastHTML is very deliberate about the objects it exports in
fasthtml.common. If it bothers you, you can import the objects you need individually, though it will make the code more verbose and less readable.If you want to learn more about how FastHTML handles imports, we cover that here.
A Minimal Charting Application
The
Scriptfunction allows you to include JavaScript. You can use Python to generate parts of your JS or JSON like this:import json from fasthtml.common import * app, rt = fast_app(hdrs=(Script(src="https://cdn.plot.ly/plotly-2.32.0.min.js"),)) data = json.dumps({ "data": [{"x": [1, 2, 3, 4],"type": "scatter"}, {"x": [1, 2, 3, 4],"y": [16, 5, 11, 9],"type": "scatter"}], "title": "Plotly chart in FastHTML ", "description": "This is a demo dashboard", "type": "scatter" }) @rt("/") def get(): return Titled("Chart Demo", Div(id="myDiv"), Script(f"var data = {data}; Plotly.newPlot('myDiv', data);")) serve()Debug Mode
When we can’t figure out a bug in FastHTML, we can run it in
DEBUGmode. When an error is thrown, the error screen is displayed in the browser. This error setting should never be used in a deployed app.from fasthtml.common import * app, rt = fast_app(debug=True) @rt("/") def get(): 1/0 return Titled("FastHTML Error!", P("Let's error!")) serve()Line 3
debug=Truesets debug mode on.Line 7
Python throws an error when it tries to divide an integer by zero.Routing
FastHTML builds upon FastAPI’s friendly decorator pattern for specifying URLs, with extra features:
main.py
from fasthtml.common import * app, rt = fast_app() @rt("/") def get(): return Titled("FastHTML", P("Let's do this!")) @rt("/hello") def get(): return Titled("Hello, world!") serve()Line 5
The “/” URL on line 5 is the home of a project. This would be accessed at 127.0.0.1:5001.Line 9
“/hello” URL on line 9 will be found by the project if the user visits 127.0.0.1:5001/hello.Tip
It looks like
get()is being defined twice, but that’s not the case. Each function decorated withrtis totally separate, and is injected into the router. We’re not calling them in the module’s namespace (locals()). Rather, we’re loading them into the routing mechanism using thertdecorator.You can do more! Read on to learn what we can do to make parts of the URL dynamic.
Variables in URLs
You can add variable sections to a URL by marking them with
{variable_name}. Your function then receives the{variable_name}as a keyword argument, but only if it is the correct type. Here’s an example:main.py
from fasthtml.common import * app, rt = fast_app() @rt("/{name}/{age}") def get(name: str, age: int): return Titled(f"Hello {name.title()}, age {age}") serve()Line 5
We specify two variable names,nameandage.Line 6
We define two function arguments named identically to the variables. You will note that we specify the Python types to be passed.Line 7
We use these functions in our project.Try it out by going to this address: 127.0.0.1:5001/uma/5. You should get a page that says,
“Hello Uma, age 5”.
What happens if we enter incorrect data?
The 127.0.0.1:5001/uma/5 URL works because
5is an integer. If we enter something that is not, such as 127.0.0.1:5001/uma/five, then FastHTML will return an error instead of a web page.FastHTML URL routing supports more complex types
The two examples we provide here use Python’s built-in
strandinttypes, but you can use your own types, including more complex ones such as those defined by libraries like attrs, pydantic, and even sqlmodel.HTTP Methods
FastHTML matches function names to HTTP methods. So far the URL routes we’ve defined have been for HTTP GET methods, the most common method for web pages.
Form submissions often are sent as HTTP POST. When dealing with more dynamic web page designs, also known as Single Page Apps (SPA for short), the need can arise for other methods such as HTTP PUT and HTTP DELETE. The way FastHTML handles this is by changing the function name.
main.py
from fasthtml.common import * app, rt = fast_app() @rt("/") def get(): return Titled("HTTP GET", P("Handle GET")) @rt("/") def post(): return Titled("HTTP POST", P("Handle POST")) serve()Line 6
On line 6 because theget()function name is used, this will handle HTTP GETs going to the/URI.Line 10
On line 10 because thepost()function name is used, this will handle HTTP POSTs going to the/URI.CSS Files and Inline Styles
Here we modify default headers to demonstrate how to use the Sakura CSS microframework instead of FastHTML’s default of Pico CSS.
main.py
from fasthtml.common import * app, rt = fast_app( pico=False, hdrs=( Link(rel='stylesheet', href='assets/normalize.min.css', type='text/css'), Link(rel='stylesheet', href='assets/sakura.css', type='text/css'), Style("p {color: red;}") )) @app.get("/") def home(): return Titled("FastHTML", P("Let's do this!"), ) serve()Line 4
By settingpicotoFalse, FastHTML will not includepico.min.css.Line 7
This will generate an HTML<link>tag for sourcing the css for Sakura.Line 8
If you want an inline styles, theStyle()function will put the result into the HTML.Other Static Media File Locations
As you saw,
ScriptandLinkare specific to the most common static media use cases in web apps: including JavaScript, CSS, and images. But it also works with videos and other static media files. The default behavior is to look for these files in the root directory - typically we don’t do anything special to include them. We can change the default directory that is looked in for files by adding thestatic_pathparameter to thefast_appfunction.app, rt = fast_app(static_path='public')FastHTML also allows us to define a route that uses
FileResponseto serve the file at a specified path. This is useful for serving images, videos, and other media files from a different directory without having to change the paths of many files. So if we move the directory containing the media files, we only need to change the path in one place. In the example below, we call images from a directory calledpublic.@rt("/{fname:path}.{ext:static}") async def get(fname:str, ext:str): return FileResponse(f'public/{fname}.{ext}')Rendering Markdown
from fasthtml.common import * hdrs = (MarkdownJS(), HighlightJS(langs=['python', 'javascript', 'html', 'css']), ) app, rt = fast_app(hdrs=hdrs) content = """ Here are some _markdown_ elements. - This is a list item - This is another list item - And this is a third list item **Fenced code blocks work here.** """ @rt('/') def get(req): return Titled("Markdown rendering example", Div(content,cls="marked")) serve()Code highlighting
Here’s how to highlight code without any markdown configuration.
from fasthtml.common import * # Add the HighlightJS built-in header hdrs = (HighlightJS(langs=['python', 'javascript', 'html', 'css']),) app, rt = fast_app(hdrs=hdrs) code_example = """ import datetime import time for i in range(10): print(f"{datetime.datetime.now()}") time.sleep(1) """ @rt('/') def get(req): return Titled("Markdown rendering example", Div( # The code example needs to be surrounded by # Pre & Code elements Pre(Code(code_example)) )) serve()Defining new
ftcomponentsWe can build our own
ftcomponents and combine them with other components. The simplest method is defining them as a function.from fasthtml.common import *def hero(title, statement): return Div(H1(title),P(statement), cls="hero") # usage example Main( hero("Hello World", "This is a hero statement") )<main> <div class="hero"> <h1>Hello World</h1> <p>This is a hero statement</p> </div> </main>Pass through components
For when we need to define a new component that allows zero-to-many components to be nested within them, we lean on Python’s
*argsand**kwargsmechanism. Useful for creating page layout controls.def layout(*args, **kwargs): """Dashboard layout for all our dashboard views""" return Main( H1("Dashboard"), Div(*args, **kwargs), cls="dashboard", ) # usage example layout( Ul(*[Li(o) for o in range(3)]), P("Some content", cls="description"), )<main class="dashboard"> <h1>Dashboard</h1> <div> <ul> <li>0</li> <li>1</li> <li>2</li> </ul> <p class="description">Some content</p> </div> </main>Dataclasses as ft components
While functions are easy to read, for more complex components some might find it easier to use a dataclass.
from dataclasses import dataclass @dataclass class Hero: title: str statement: str def __ft__(self): """ The __ft__ method renders the dataclass at runtime.""" return Div(H1(self.title),P(self.statement), cls="hero") # usage example Main( Hero("Hello World", "This is a hero statement") )<main> <div class="hero"> <h1>Hello World</h1> <p>This is a hero statement</p> </div> </main>Testing views in notebooks
Because of the ASGI event loop it is currently impossible to run FastHTML inside a notebook. However, we can still test the output of our views. To do this, we leverage Starlette, an ASGI toolkit that FastHTML uses.
# First we instantiate our app, in this case we remove the # default headers to reduce the size of the output. app, rt = fast_app(default_hdrs=False) # Setting up the Starlette test client from starlette.testclient import TestClient client = TestClient(app) # Usage example @rt("/") def get(): return Titled("FastHTML is awesome", P("The fastest way to create web apps in Python")) print(client.get("/").text)<!doctype html> <html> <head> <title>FastHTML is awesome</title> </head> <body> <main class="container"> <h1>FastHTML is awesome</h1> <p>The fastest way to create web apps in Python</p> </main> </body> </html>Forms
To validate data coming from users, first define a dataclass representing the data you want to check. Here’s an example representing a signup form.
from dataclasses import dataclass @dataclass class Profile: email:str; phone:str; age:intCreate an FT component representing an empty version of that form. Don’t pass in any value to fill the form, that gets handled later.
profile_form = Form(method="post", action="/profile")( Fieldset( Label('Email', Input(name="email")), Label("Phone", Input(name="phone")), Label("Age", Input(name="age")), ), Button("Save", type="submit"), ) profile_form<form enctype="multipart/form-data" method="post" action="/profile"><fieldset><label>Email <input name="email"> </label><label>Phone <input name="phone"> </label><label>Age <input name="age"> </label></fieldset><button type="submit">Save</button></form>Once the dataclass and form function are completed, we can add data to the form. To do that, instantiate the profile dataclass:
profile = Profile([EMAIL_ADDRESS]', phone='[PHONE_NUMBER]', age=5) profileProfile([EMAIL_ADDRESS]', phone='[PHONE_NUMBER]', age=5)Then add that data to the
profile_formusing FastHTML’sfill_formclass:fill_form(profile_form, profile)<form enctype="multipart/form-data" method="post" action="/profile"><fieldset><label>Email <input name="email" value="[EMAIL_ADDRESS]"> </label><label>Phone <input name="phone" value="[PHONE_NUMBER]"> </label><label>Age <input name="age" value="5"> </label></fieldset><button type="submit">Save</button></form>Forms with views
The usefulness of FastHTML forms becomes more apparent when they are combined with FastHTML views. We’ll show how this works by using the test client from above. First, let’s create a SQlite database:
db = database("profiles.db") profiles = db.create(Profile, pk="email")Now we insert a record into the database:
profiles.insert(profile)Profile([EMAIL_ADDRESS]', phone='[PHONE_NUMBER]', age=5)And we can then demonstrate in the code that form is filled and displayed to the user.
@rt("/profile/{email}") def profile(email:str): profile = profiles[email] filled_profile_form = fill_form(profile_form, profile) return Titled(f'Profile for {profile.email}', filled_profile_form) print(client.get(f"[EMAIL_ADDRESS]").text)Line 3
Fetch the profile using the profile table’semailprimary keyLine 4
Fill the form for display.<!doctype html> <html> <head> <title>Profile for [EMAIL_ADDRESS]</title> </head> <body> <main class="container"> <h1>Profile for [EMAIL_ADDRESS]</h1> <form enctype="multipart/form-data" method="post" action="/profile"><fieldset><label>Email <input name="email" value="[EMAIL_ADDRESS]"> </label><label>Phone <input name="phone" value="[PHONE_NUMBER]"> </label><label>Age <input name="age" value="5"> </label></fieldset><button type="submit">Save</button></form></main> </body> </html>And now let’s demonstrate making a change to the data.
@rt("/profile") def post(profile: Profile): profiles.update(profile) return RedirectResponse(url=f"/profile/{profile.email}") new_data = dict([EMAIL_ADDRESS]', phone='[PHONE_NUMBER]', age=25) print(client.post("/profile", data=new_data).text)Line 2
We use theProfiledataclass definition to set the type for the incomingprofilecontent. This validates the field types for the incoming dataLine 3
Taking our validated data, we updated the profiles tableLine 4
We redirect the user back to their profile viewLine 7
The display is of the profile form view showing the changes in data.<!doctype html> <html> <head> <title>Profile for [EMAIL_ADDRESS]</title> </head> <body> <main class="container"> <h1>Profile for [EMAIL_ADDRESS]</h1> <form enctype="multipart/form-data" method="post" action="/profile"><fieldset><label>Email <input name="email" value="[EMAIL_ADDRESS]"> </label><label>Phone <input name="phone" value="[PHONE_NUMBER]"> </label><label>Age <input name="age" value="25"> </label></fieldset><button type="submit">Save</button></form></main> </body> </html>Strings and conversion order
The general rules for rendering are: -
__ft__method will be called (for default components likeP,H2, etc. or if you define your own components) - If you pass a string, it will be escaped - On other python objects,str()will be calledAs a consequence, if you want to include plain HTML tags directly into e.g. a
Div()they will get escaped by default (as a security measure to avoid code injections). This can be avoided by usingNotStr(), a convenient way to reuse python code that returns already HTML. If you use pandas, you can usepandas.DataFrame.to_html()to get a nice table. To include the output a FastHTML, wrap it inNotStr(), likeDiv(NotStr(df.to_html())).Above we saw how a dataclass behaves with the
__ft__method defined. On a plain dataclass,str()will be called (but not escaped).from dataclasses import dataclass @dataclass class Hero: title: str statement: str # rendering the dataclass with the default method Main( Hero("<h1>Hello World</h1>", "This is a hero statement") )<main>Hero(title='<h1>Hello World</h1>', statement='This is a hero statement')</main># This will display the HTML as text on your page Div("Let's include some HTML here: <div>Some HTML</div>")<div>Let's include some HTML here: <div>Some HTML</div></div># Keep the string untouched, will be rendered on the page Div(NotStr("<div><h1>Some HTML</h1></div>"))<div><div><h1>Some HTML</h1></div></div>Custom exception handlers
FastHTML allows customization of exception handlers, but does so gracefully. What this means is by default it includes all the
<html>tags needed to display attractive content. Try it out!from fasthtml.common import * def not_found(req, exc): return Titled("404: I don't exist!") exception_handlers = {404: not_found} app, rt = fast_app(exception_handlers=exception_handlers) @rt('/') def get(): return (Titled("Home page", P(A(href="/oops")("Click to generate 404 error")))) serve()We can also use lambda to make things more terse:
from fasthtml.common import * exception_handlers={ 404: lambda req, exc: Titled("404: I don't exist!"), 418: lambda req, exc: Titled("418: I'm a teapot!") } app, rt = fast_app(exception_handlers=exception_handlers) @rt('/') def get(): return (Titled("Home page", P(A(href="/oops")("Click to generate 404 error")))) serve()Cookies
We can set cookies using the
cookie()function. In our example, we’ll create atimestampcookie.from datetime import datetime from IPython.display import HTML@rt("/settimestamp") def get(req): now = datetime.now() return P(f'Set to {now}'), cookie('now', datetime.now()) HTML(client.get('/settimestamp').text)Now let’s get it back using the same name for our parameter as the cookie name.
@rt('/gettimestamp') def get(now:parsed_date): return f'Cookie was set at time {now.time()}' client.get('/gettimestamp').text'Cookie was set at time 15:33:48.141903'Sessions
For convenience and security, FastHTML has a mechanism for storing small amounts of data in the user’s browser. We can do this by adding a
sessionargument to routes. FastHTML sessions are Python dictionaries, and we can leverage to our benefit. The example below shows how to concisely set and get sessions.@rt('/adder/{num}') def get(session, num: int): session.setdefault('sum', 0) session['sum'] = session.get('sum') + num return Response(f'The sum is {session["sum"]}.')Toasts (also known as Messages)
Toasts, sometimes called “Messages” are small notifications usually in colored boxes used to notify users that something has happened. Toasts can be of four types:
- info
- success
- warning
- error
Examples toasts might include:
- “Payment accepted”
- “Data submitted”
- “Request approved”
Toasts require the use of the
setup_toasts()function plus every view needs these two features:- The session argument
- Must return FT components
setup_toasts(app) @rt('/toasting') def get(session): # Normally one toast is enough, this allows us to see # different toast types in action. add_toast(session, f"Toast is being cooked", "info") add_toast(session, f"Toast is ready", "success") add_toast(session, f"Toast is getting a bit crispy", "warning") add_toast(session, f"Toast is burning!", "error") return Titled("I like toast")Line 1
setup_toastsis a helper function that adds toast dependencies. Usually this would be declared right afterfast_app()Line 4
Toasts require sessionsLine 11
Views with Toasts must return FT or FtResponse components.💡
setup_toaststakes adurationinput that allows you to specify how long a toast will be visible before disappearing. For examplesetup_toasts(duration=5)sets the toasts duration to 5 seconds. By default toasts disappear after 10 seconds.Authentication and authorization
In FastHTML the tasks of authentication and authorization are handled with Beforeware. Beforeware are functions that run before the route handler is called. They are useful for global tasks like ensuring users are authenticated or have permissions to access a view.
First, we write a function that accepts a request and session arguments:
# Status code 303 is a redirect that can change POST to GET, # so it's appropriate for a login page. login_redir = RedirectResponse('/login', status_code=303) def user_auth_before(req, sess): # The `auth` key in the request scope is automatically provided # to any handler which requests it, and can not be injected # by the user using query params, cookies, etc, so it should # be secure to use. auth = req.scope['auth'] = sess.get('auth', None) # If the session key is not there, it redirects to the login page. if not auth: return login_redirNow we pass our
user_auth_beforefunction as the first argument into aBeforewareclass. We also pass a list of regular expressions to theskipargument, designed to allow users to still get to the home and login pages.beforeware = Beforeware( user_auth_before, skip=[r'/favicon\.ico', r'/static/.*', r'.*\.css', r'.*\.js', '/login', '/'] ) app, rt = fast_app(before=beforeware)Server-sent events (SSE)
With server-sent events, it’s possible for a server to send new data to a web page at any time, by pushing messages to the web page. Unlike WebSockets, SSE can only go in one direction: server to client. SSE is also part of the HTTP specification unlike WebSockets which uses its own specification.
FastHTML introduces several tools for working with SSE which are covered in the example below. While concise, there’s a lot going on in this function so we’ve annotated it quite a bit.
import random from asyncio import sleep from fasthtml.common import * hdrs=(Script(src="https://unpkg.com/htmx-ext-sse@2.2.1/sse.js"),) app,rt = fast_app(hdrs=hdrs) @rt def index(): return Titled("SSE Random Number Generator", P("Generate pairs of random numbers, as the list grows scroll downwards."), Div(hx_ext="sse", sse_connect="/number-stream", hx_swap="beforeend show:bottom", sse_swap="message")) shutdown_event = signal_shutdown() async def number_generator(): while not shutdown_event.is_set(): data = Article(random.randint(1, 100)) yield sse_message(data) await sleep(1) @rt("/number-stream") async def get(): return EventStream(number_generator())Line 5
Import the HTMX SSE extensionLine 12
Tell HTMX to load the SSE extensionLine 13
Look at the/number-streamendpoint for SSE contentLine 14
When new items come in from the SSE endpoint, add them at the end of the current content within the div. If they go beyond the screen, scroll downwardsLine 15
Specify the name of the event. FastHTML’s default event name is “message”. Only change if you have more than one call to SSE endpoints within a viewLine 17
Set up the asyncio event loopLine 19
Don’t forget to make this anasyncfunction!Line 20
Iterate through the asyncio event loopLine 22
We yield the data. Data ideally should be comprised of FT components as that plugs nicely into HTMX in the browserLine 26
The endpoint view needs to be an async function that returns aEventStreamWebsockets
With websockets we can have bi-directional communications between a browser and client. Websockets are useful for things like chat and certain types of games. While websockets can be used for single direction messages from the server (i.e. telling users that a process is finished), that task is arguably better suited for SSE.
FastHTML provides useful tools for adding websockets to your pages.
from fasthtml.common import * from asyncio import sleep app, rt = fast_app(exts='ws') def mk_inp(): return Input(id='msg', autofocus=True) @rt('/') async def get(request): cts = Div( Div(id='notifications'), Form(mk_inp(), id='form', ws_send=True), hx_ext='ws', ws_connect='/ws') return Titled('Websocket Test', cts) async def on_connect(send): print('Connected!') await send(Div('Hello, you have connected', id="notifications")) async def on_disconnect(ws): print('Disconnected!') @app.ws('/ws', conn=on_connect, disconn=on_disconnect) async def ws(msg:str, send): await send(Div('Hello ' + msg, id="notifications")) await sleep(2) return Div('Goodbye ' + msg, id="notifications"), mk_inp()Line 4
To use websockets in FastHTML, you must instantiate the app withextsset to ‘ws’Line 6
As we want to use websockets to reset the form, we define themk_inputfunction that can be called from multiple locationsLine 12
We create the form and mark it with thews_sendattribute, which is documented here in the HTMX websocket specification. This tells HTMX to send a message to the nearest websocket based on the trigger for the form element, which for forms is pressing theenterkey, an action considered to be a form submissionLine 13
This is where the HTMX extension is loaded (hx_ext='ws') and the nearest websocket is def - Assistant
FastHTML is a Python library designed for building server-rendered hypermedia applications by integrating Starlette, Uvicorn, HTMX, and fastcore's
FT"FastTags". It offers a decorator-based routing system, Beforeware functionality, automaticFTto HTML rendering, and more. TheFastHTMLclass inherits fromStarlette, providing a robust foundation for web development.Key Features:
- Routing: Utilizes decorators to define routes, supporting dynamic URL segments and multiple HTTP methods.
- Component-Based Structure: Encourages the creation of reusable components using
FT"FastTags" for efficient development. - Integration with HTMX: Facilitates the inclusion of dynamic behaviors in web pages without writing extensive JavaScript.
- Beforeware: Allows for pre-processing of requests, useful for tasks like authentication and logging.
- Automatic Rendering: Automatically converts
FTcomponents to HTML, streamlining the development process.
Getting Started:
To begin using FastHTML:
-
Installation: Install the library using pip:
pip install python-fasthtml -
Minimal Application: Create a file named
main.pywith the following content:from fasthtml.common import * app, rt = fast_app() @rt("/") def get(): return Titled("FastHTML", P("Let's do this!")) serve()Running this script with
python main.pywill start a server athttp://localhost:5001, displaying a page with the title "FastHTML" and the message "Let's do this!".
Additional Resources:
- Official Documentation: For comprehensive guides and API references, visit the FastHTML Documentation.
- Community Support: Join the FastHTML Discord Community to ask questions, share your work, and learn from others.
By leveraging FastHTML, developers can build interactive and scalable web applications efficiently, utilizing Python's full capabilities alongside modern web technologies.
- User
I can I have a header and footer have a cool gradient from dark blue to dark green?
- Assistant
To create a header and footer with a gradient transitioning from dark blue to dark green in your FastHTML application, you can utilize CSS gradients. Here's how you can implement this:
-
Define the Gradient in CSS:
First, create a CSS file (e.g.,
styles.css) and define the gradient for the header and footer:/* styles.css */ header, footer { background: linear-gradient(to right, #01048B, #016102); /* Dark Blue to Dark Green */ color: white; padding: 20px; text-align: center; }In this CSS:
#01048Brepresents a dark blue color.#016102represents a dark green color.linear-gradient(to right, #01048B, #016102)creates a horizontal gradient from dark blue to dark green.color: white;ensures the text is readable against the dark background.padding: 20px;adds space inside the header and footer.text-align: center;centers the text horizontally.
-
Include the CSS in Your FastHTML Application:
Modify your FastHTML application to include the CSS file:
from fasthtml.common import * app, rt = fast_app( hdrs=( Link(rel='stylesheet', href='/static/styles.css'), # ... other headers ) ) @rt("/") def get(): return Titled("FastHTML with Gradient Header and Footer", Div( header("Welcome to My Website"), P("This is the main content."), footer("Footer Content") ) ) serve()In this setup:
Link(rel='stylesheet', href='/static/styles.css')includes the external CSS file.header("Welcome to My Website")andfooter("Footer Content")are custom components that render the header and footer content.
-
Serve the Static CSS File:
Ensure that the
styles.cssfile is placed in a directory namedstaticwithin your project structure. FastHTML will automatically serve static files from this directory.
By following these steps, your header and footer will display a smooth gradient transitioning from dark blue to dark green, enhancing the visual appeal of your FastHTML application.
-
- User
No, in FASTHtml
- Assistant
To create a header and footer with a gradient transitioning from dark blue to dark green in your FastHTML application, you can define a custom layout that includes these styles. Here's how you can implement this:
-
Define the Gradient in CSS:
First, create a CSS file (e.g.,
styles.css) and define the gradient for the header and footer:/* styles.css */ header, footer { background: linear-gradient(to right, #01048B, #016102); /* Dark Blue to Dark Green */ color: white; padding: 20px; text-align: center; }In this CSS:
#01048Brepresents a dark blue color.#016102represents a dark green color.linear-gradient(to right, #01048B, #016102)creates a horizontal gradient from dark blue to dark green.color: white;ensures the text is readable against the dark background.padding: 20px;adds space inside the header and footer.text-align: center;centers the text horizontally.
-
Include the CSS in Your FastHTML Application:
Modify your FastHTML application to include the CSS file:
from fasthtml.common import * app, rt = fast_app( hdrs=( Link(rel='stylesheet', href='/static/styles.css'), # ... other headers ) ) @rt("/") def get(): return Titled("FastHTML with Gradient Header and Footer", Div( header("Welcome to My Website"), P("This is the main content."), footer("Footer Content") ) ) serve()In this setup:
Link(rel='stylesheet', href='/static/styles.css')includes the external CSS file.header("Welcome to My Website")andfooter("Footer Content")are custom components that render the header and footer content.
-
Serve the Static CSS File:
Ensure that the
styles.cssfile is placed in a directory namedstaticwithin your project structure. FastHTML will automatically serve static files from this directory.
By following these steps, your header and footer will display a smooth gradient transitioning from dark blue to dark green, enhancing the visual appeal of your FastHTML application.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.