using Microsoft.AspNetCore.Antiforgery;
namespace Htmx.ApiDemo;
///
/// Renders a full page or just the body component depending on whether
/// the request was made by HTMX (HX-Request header present).
///
/// Full request → wraps body in MainLayout (complete HTML page)
/// HTMX request → renders body only + sets HX-Title so the browser
/// tab title still updates
///
public static class HtmxPageExtensions
{
public static HtmxResult WriteHtmxPage(
this HttpContext ctx,
IHtmxComponent body,
string title = "App",
string appName = "HtmxApp",
string pageTitle = "")
{
if (ctx.Request.Headers.ContainsKey("HX-Request"))
{
ctx.Response.Headers["HX-Title"] = title;
return ctx.WriteHtmxBody(body);
}
else
{
string? userName = ctx.User.Identity?.IsAuthenticated == true
? (ctx.User.FindFirst("DisplayName")?.Value
?? ctx.User.FindFirst(System.Security.Claims.ClaimTypes.Name)?.Value)
: null;
var antiforgery = ctx.RequestServices.GetRequiredService();
var afTokens = antiforgery.GetAndStoreTokens(ctx);
return ctx.WriteHtmxBody(new Templates.MainLayout(body, title, appName, pageTitle, userName, afTokens.RequestToken));
}
}
}