Source Generators
Eliminate magic strings with zero-config type safety.
The Problem with Magic Strings
HTMX development relies heavily on string identifiers: Event names, View names, and Element IDs.
// ❌ Brittle, typo-prone, hard to refactor
return SwapResponse()
.AlsoUpdate("product-list", "_ProductList", items) // Did you mean "products-list"?
.Build();
The Solution: Compile-Time constants
Swap.Htmx includes C# Source Generators that run during your build. They scan your project and generate type-safe constants for you.
Zero Configuration
By default, the generator scans any .cshtml file in your Views, Pages, or Modules folders.
It generates two primary static classes:
SwapViews: Constants for your view paths.SwapElements: Constants for HTML Element IDs found in your views.
1. Type-Safe Views
The generator groups views by their Controller (folder name).
// Generated Code (Automatic)
public static class SwapViews
{
public static class Home
{
public const string Index = "Index";
public const string _Features = "_Features";
}
public static class Products
{
public const string List = "List";
public const string _Card = "_Card";
}
}
Usage:
// ✅ No more typos. IntelliSense tailored to your project.
return SwapView(SwapViews.Products.List);
2. Type-Safe Element IDs
The generator parses your HTML and extracts id="..." attributes. It filters out dynamic IDs (containing @) and common framework IDs to keep the list clean.
Before (View):
<div id="product-grid">
<span id="cart-count">0</span>
</div>
After (Controller):
// ✅ Generated constants
builder.AlsoUpdate(SwapElements.ProductGrid, ...);
builder.AlsoUpdate(SwapElements.CartCount, ...);
3. Type-Safe Events
For events, you can opt-in to generation by decorating a partial class with [SwapEventSource].
[SwapEventSource]
public static partial class UserEvents
{
public const string UserCreated = "user.created";
public const string UserDeleted = "user.deleted";
}
This generates a nested, strongly-typed structure: UserEvents.User.Created which is a EventKey type (not a string), preventing it from being used where a View name is expected.
Troubleshooting
"SwapViews" does not exist?
- Ensure you have built the project (
dotnet build). Generators run during the build. - Check your
.csprojensures the generator is included (it is by default in the package). - Restart VS Code / Visual Studio to refresh IntelliSense.
Excluding IDs
If you have IDs you don't want generated (like JS-only hooks), prefix them with js- or configure exclusions in Directory.Build.props (Advanced).