Skip to content

Commit

Permalink
feat: ConditionalComponentBase, which will output when context.Reques…
Browse files Browse the repository at this point in the history
…t.IsFullPageRequest || directConditionalChildren == 0
  • Loading branch information
egil committed May 3, 2024
1 parent 59527ae commit 606a807
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 4 deletions.
12 changes: 8 additions & 4 deletions samples/MinimalHtmxorApp/Components/Pages/Counter.razor
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
@page "/counter"
@inherits ConditionalComponentBase
<PageTitle>Counter</PageTitle>

<h1>Counter</h1>
<p>
This is a htmx enabled counter. It uses the <code>&lt;HtmxPartial&gt;</code> to
enable the concept <a href="https://htmx.org/essays/template-fragments/" target="_blank">template fragments</a>.
This is a htmx enabled counter.
</p>
<p>
When Htmxor sees a <code>&lt;HtmxPartial&gt;</code> component, it will only render it's content, and not the surrounding
content, like these paragraph elements.
During a htmx requests, the elements in this component will not be rendered (this paragraph), because the component
inherits from <code>ConditionalComponentBase</code>. Child components, like the <code>HtmxPartial</code> component,
will render out its markup during htmx requests and during normal requests.
</p>
<p>
This declaratively enable the concept <a href="https://htmx.org/essays/template-fragments/" target="_blank">template fragments</a>.
</p>

<div id="counter">
Expand Down
18 changes: 18 additions & 0 deletions src/Htmxor/Components/ConditionalComponentBase.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Htmxor.Http;
using Microsoft.AspNetCore.Components;

namespace Htmxor.Components;

public abstract class ConditionalComponentBase : ComponentBase, IConditionalOutputComponent
{
/// <inheritdoc/>
/// <remarks>The <see cref="ConditionalComponentBase"/> defaults to returning <see langword="true"/>
/// when the request is a full page request or if there are no direct conditional children.</remarks>
public virtual bool ShouldOutput([NotNull] HtmxContext context, int directConditionalChildren, int conditionalChildren)
=> context.Request.IsFullPageRequest || directConditionalChildren == 0;
}

0 comments on commit 606a807

Please sign in to comment.