π§© Template
Templates allow you to define reusable wrappers for shared UI components β like navigation bars, sidebars, headers, or htmx
elements β that are used across multiple pages. This eliminates the need to copy and paste the same htmx
logic over and over again in different files.
Templates ensure that shared UI elements are persistent between pages, which enables smooth transitions like animations, folding navbars, and shared loading states without re-rendering the entire component.
β
Why Use Templates?
DRY Code: Avoid duplicating
htmx
-heavy UI code on every page.Smooth Transitions: Shared components like navbars stay mounted between page navigations.
Cleaner Pages: Each page file focuses only on its unique content.
π οΈ Defining a Template
To define a template, go to src/_components/templateProvider.tsx
and add a new function e.g DashboardTemplate
function DashboardTemplate({ children }: { children: React.ReactNode }) {
return (
<div className="w-full h-full flex flex-row bg-white">
<div className="w-full h-full flex flex-col md:flex-row">
<Navbar/>
<div className="md:flex-grow h-full text-black">
<Middleware>
{children}
</Middleware>
</div>
</div>
</div>
)
}
Than add the name of the template into the templates object and into the Template type, so in this case that would be dashboard
const Templates = {
dashboard: DashboardTemplate,
plain: PlainTemplate
}
type Template = 'dashboard' | 'plain';
π Using a Template in a Page
To apply a template to a page, add an template
export in the pageβs file, like so:
import { useTemplate } from "src/_components/templateProvider";
import { useEffect } from "react";
export default function App() {
const { setTemplate } = useTemplate();
useEffect(() => {
setTemplate('dashboard');
}, []);
return (
<div>Hello!!!</div>
)
}
You need to enter the template name so in our case dashboard into the setTemplate function.
When you want to use a page without a template you need to do the same as above but than you enter the plain template else it would still have the previous template shown on that page.
Last updated