Skip to content

Standalone {{^}} is not treated as the else separator inside blocks ({{#if}}, {{#each}}, sections) #672

Closed

Description

@hidingmyname

Describe the bug

Location (Handlebars-Net/Handlebars.Net @ c9a20a2):

                switch (item)
                {
                    case Expression _:
                        yield return item;
                        continue;
                    case WordExpressionToken word when IsRegisteredHelperName(word.Value):
                        yield return HandlebarsExpression.Helper(word.Value, false, isRaw, word.Context);
                        break;
                    ...
                    default:
                        yield return item;
                        break;
                }
        private bool IsElseBlock(Expression item)
        {
            item = UnwrapStatement(item);
            return item is HelperExpression && ((HelperExpression)item).HelperName == "else";
        }

Problem

In Handlebars, a bare {{^}} inside a block is the inverse separator, the same as {{else}}: {{#if c}}yes{{^}}no{{/if}}, {{#each items}}...{{^}}none{{/each}}, {{#val}}yes{{^}}no{{/val}}. In Handlebars.Net the caret is never turned into the else marker. It ends up as a path expression that prints the current context, and the text after it stays in the main body:

  • {{#if condition}}yes{{^}}no{{/if}} with condition = true renders yes{ condition = True }no instead of yes.
  • {{#each people}}{{name}}{{^}}No one{{/each}} renders Alice{ name = Alice }No one for one person.
  • For a falsy section ({{#val}}yes{{^}}no{{/val}}, val = false) there is no inverse block, so the output is empty instead of no.

This only affects the bare {{^}}. Named inverted sections ({{^name}}...{{/name}}) work, and {{else}} is a workaround. The repository already records this as a known spec gap ("Gap 5" in Handlebars.Test/HandlebarsSpec.md, with InvertedSection_InlineCaretSyntax asserting the current output), but I could not find an issue that tracks it.

Expected behavior:

{{^}} inside a block behaves exactly like {{else}}: {{#if condition}}yes{{^}}no{{/if}} renders yes for true and no for false, and {{#each}}...{{^}}...{{/each}} renders the inverse for an empty sequence.

Test to reproduce

[Theory, ClassData(typeof(HandlebarsEnvGenerator))]
public void InvertedSection_InlineCaretSyntaxInIf(IHandlebars hbs)
{
    var template = hbs.Compile("{{#if condition}}yes{{^}}no{{/if}}");
    Assert.Equal("yes", template(new { condition = true }));
    Assert.Equal("no", template(new { condition = false }));
}

[Theory, ClassData(typeof(HandlebarsEnvGenerator))]
public void InvertedSection_InlineCaretSyntaxInEach(IHandlebars hbs)
{
    var template = hbs.Compile("{{#each people}}{{name}}{{^}}No one{{/each}}");
    Assert.Equal("Alice", template(new { people = new[] { new { name = "Alice" } } }));
    Assert.Equal("No one", template(new { people = Array.Empty<object>() }));
}

Run from source/: dotnet test Handlebars.Test/Handlebars.Test.csproj --filter "FullyQualifiedName~InvertedSection_InlineCaret" (together with InvertedSection_InlineCaretSyntax rewritten to expect yes / no):

  Failed HandlebarsDotNet.Test.HandlebarsSpecCoverageTests.InvertedSection_InlineCaretSyntax(hbs: HandlebarsEnvironment { Configuration = HandlebarsConfiguration { AliasProviders = [···], BlockDecorators = [···], BlockHelpers = [···], Compatibility = Compatibility { ··· }, CompileTimeConfiguration = CompileTimeConfiguration { ··· }, ··· }, IsSharedEnvironment = False }) [12 ms]
  Error Message:
   Assert.Equal() Failure: Strings differ
Expected: "yes"
Actual:   "yes{ val &#x3D; True }no"
...
  Failed HandlebarsDotNet.Test.HandlebarsSpecCoverageTests.InvertedSection_InlineCaretSyntaxInIf(hbs: HandlebarsEnvironment { Configuration = HandlebarsConfiguration { AliasProviders = [···], BlockDecorators = [···], BlockHelpers = [···], Compatibility = Compatibility { ··· }, CompileTimeConfiguration = CompileTimeConfiguration { ··· }, ··· }, IsSharedEnvironment = False }) [178 ms]
   Assert.Equal() Failure: Strings differ
Expected: "yes"
Actual:   "yes{ condition &#x3D; True }no"
...
  Failed HandlebarsDotNet.Test.HandlebarsSpecCoverageTests.InvertedSection_InlineCaretSyntaxInEach(hbs: HandlebarsEnvironment { Configuration = HandlebarsConfiguration { AliasProviders = [···], BlockDecorators = [···], BlockHelpers = [···], Compatibility = Compatibility { ··· }, CompileTimeConfiguration = CompileTimeConfiguration { ··· }, ··· }, IsSharedEnvironment = False }) [11 ms]
   Assert.Equal() Failure: Strings differ
Expected: "Alice"
Actual:   "Alice{ name &#x3D; Alice }No one"
...
Failed!  - Failed:    15, Passed:     0, Skipped:     0, Total:    15, Duration: 279 ms - Handlebars.Test.dll (net10.0)

Environment:

  • Commit: c9a20a29529a; the lexer/converter files are unchanged on current master (b4b0296)
  • Toolchain: .NET SDK 10.0.403 (runtime 10.0.14), net10.0, Linux x64

Other related info

Already fixed in handlebars-lang/handlebars.js

PR: handlebars-lang/handlebars.js#834 — "Refactor blocks, programs and inverses" (merged 2014-08-23T21:30:28Z, merge commit a2190ba5bb8). As part of that refactor the tokenizer emits the same INVERSE token for a standalone {{^}} and for {{else}}, so both split a block the same way.

How handlebars.js fixed it (relevant hunks, verbatim):

--- a/src/handlebars.l
+++ b/src/handlebars.l
@@ -75,6 +75,8 @@ ID    [^\s!"#%-,\.\/;->@\[-\^`\{-~]+/{LOOKAHEAD}
 <mu>"{{"{LEFT_STRIP}?">"         return 'OPEN_PARTIAL';
 <mu>"{{"{LEFT_STRIP}?"#"         return 'OPEN_BLOCK';
 <mu>"{{"{LEFT_STRIP}?"/"         return 'OPEN_ENDBLOCK';
+<mu>"{{"{LEFT_STRIP}?"^"\s*{RIGHT_STRIP}?"}}"        this.popState(); return 'INVERSE';
+<mu>"{{"{LEFT_STRIP}?\s*"else"\s*{RIGHT_STRIP}?"}}"  this.popState(); return 'INVERSE';
 <mu>"{{"{LEFT_STRIP}?"^"         return 'OPEN_INVERSE';
 <mu>"{{"{LEFT_STRIP}?\s*"else"   return 'OPEN_INVERSE';
 <mu>"{{"{LEFT_STRIP}?"{"         return 'OPEN_UNESCAPED';
--- a/src/handlebars.yy
+++ b/src/handlebars.yy
...
+inverseAndProgram
+  : INVERSE program -> { strip: yy.stripFlags($1, $1), program: $2 }
   ;
...
 simpleInverse
-  : OPEN_INVERSE CLOSE -> stripFlags($1, $2)
+  : INVERSE -> yy.stripFlags($1, $1)
   ;

Suggested fix

Turn the bare ^ word (it is only produced for {{^}}, {{^ }} or {{~^~}}, because {{^name}} yields ^name) into the same else helper expression that {{else}} produces, so every block accumulator and the standalone-whitespace handling treat it as the separator:

diff --git a/source/Handlebars/Compiler/Lexer/Converter/HelperConverter.cs b/source/Handlebars/Compiler/Lexer/Converter/HelperConverter.cs
--- a/source/Handlebars/Compiler/Lexer/Converter/HelperConverter.cs
+++ b/source/Handlebars/Compiler/Lexer/Converter/HelperConverter.cs
@@ -48,6 +48,10 @@ namespace HandlebarsDotNet.Compiler
                     case Expression _:
                         yield return item;
                         continue;
+                    case WordExpressionToken word when !isRaw && word.Value == "^":
+                        // standalone {{^}} is the inverse separator, same as {{else}}
+                        yield return HandlebarsExpression.Helper("else", false, isRaw, word.Context);
+                        break;
                     case WordExpressionToken word when IsRegisteredHelperName(word.Value):
                         yield return HandlebarsExpression.Helper(word.Value, false, isRaw, word.Context);
                         break;

Verified on c9a20a2 (.NET SDK 10.0.403, net10.0): the tests above fail without this patch and pass with it; no other test results change (dotnet test Handlebars.Test/Handlebars.Test.csproj). The test change rewrites InvertedSection_InlineCaretSyntax to expect yes / no and removes "Gap 5" from HandlebarsSpec.md. A stray {{^}} outside any block now behaves like a stray {{else}} instead of printing the context.

I can submit a PR for this.

Checked: searches for {{^}}, caret else inverse and standalone caret found no existing issue or PR; the gap is only recorded in the test suite and HandlebarsSpec.md.

Activity

  1. rexm commented on Nov 7, 2026

    @rexm
    Member

    Nudging my helperbot to take a look at this

    /harness adopt

  2. stencil-harness commented on Nov 7, 2026

    @stencil-harness
    Contributor

    I'm the agent handling issue intake on Rex's behalf. My understanding: a standalone {{^}} inside a block should act as the inverse separator exactly like {{else}}, but today it renders as a path expression. I'll evaluate whether I can address this autonomously and report back.

  3. stencil-harness commented on Nov 7, 2026

    @stencil-harness
    Contributor

    I'm unable to proceed further on this and am awaiting follow-up from a human maintainer.

  4. stencil-harness commented on Nov 7, 2026

    @stencil-harness
    Contributor

    A standalone {{^}} now works as the inverse separator, exactly like {{else}}. The fix is on branch claude/issue-672 (commit 8e2fee6) and has not been shipped: there is no merge or release, and it's waiting for maintainer review.

    What changed (Handlebars-Net/Handlebars.Net):

    • A bare {{^}}, {{^ }} or {{~^~}} is now treated as the same else marker that {{else}} produces. This works in #if, #unless, #each, #with, sections and custom block helpers.
    • The new step lives in InverseSeparatorConverter. It runs after raw blocks are processed, so {{^}} inside {{{{raw}}}}...{{{{/raw}}}} stays literal text. Putting it in HelperConverter, as the issue suggested, would have made it render as {{else}} inside raw blocks.
    • InvertedSection_InlineCaretSyntax now expects yes / no. New tests cover each block type, the whitespace and ~ forms, a tag on its own line, and raw blocks. "Gap 5" is removed from HandlebarsSpec.md.

    Verification: the full test suite passes (2183 tests, 0 failures). With the new step disabled, 45 of the 46 new test cases fail. The one that still passes is the raw-block test, which checks that raw blocks are left alone.

    Behavior change to be aware of: a stray {{^}} outside any block now renders nothing, the same as a stray {{else}}. Before, it printed the current context's ToString().

    Separate bug I noticed but didn't fix (already on master): with Compatibility.RelaxedHelperNaming = true, every raw block fails to compile, for example {{{{raw}}}}a{{foo}}b{{{{/raw}}}}. It is unrelated to this change.

  5. rexm commented on Nov 7, 2026

    @rexm
    Member

    Elaborate on "with the new step disabled, 45 of 46 new test cases fail", and please show simple before-and-after examples of the behavior change.

  6. stencil-harness commented on Nov 7, 2026

    @stencil-harness
    Contributor

    What "45 of 46 fail" means

    The new tests make up 46 test cases:

    • Nine tests run once in each of the 5 standard test environments (HandlebarsEnvGenerator), giving 45 cases:
      • InvertedSection_InlineCaretSyntax
      • ...InListSection, ...InIf, ...InUnless, ...InEach, ...InWith, ...InCustomBlockHelper
      • ...WithWhitespace, ...StandaloneLine
    • One single test, InvertedSection_InlineCaretSyntaxIsLiteralInsideRawBlock, makes 46.

    I removed the one line that runs InverseSeparatorConverter in ExpressionBuilder and ran the tests again. All 45 cases from the nine tests failed, in every environment. The raw-block test still passed. That is expected: it doesn't test the fix. It makes sure {{^}} inside a raw block stays literal text, which was already the case before and still is. The full suite (2183 tests) passes with the change in place.

    Before and after (default environment, actual output from both builds)

    Template Data Before After
    {{#if condition}}yes{{^}}no{{/if}} condition = true yes{ condition &#x3D; True }no yes
    {{#if condition}}yes{{^}}no{{/if}} condition = false (empty) no
    {{#each people}}{{name}}{{^}}No one{{/each}} one person, Alice Alice{ name &#x3D; Alice }No one Alice
    {{#each people}}{{name}}{{^}}No one{{/each}} empty list (empty) No one
    {{#val}}yes{{^}}no{{/val}} val = true yes{ val &#x3D; True }no yes
    {{#val}}yes{{^}}no{{/val}} val = false (empty) no
    a{{^}}b (stray, outside any block) x = 1 a{ x &#x3D; 1 }b ab (same as a stray {{else}})
    {{{{raw}}}}a{{^}}b{{{{/raw}}}} — a{{^}}b a{{^}}b (unchanged)

    Before the fix, {{^}} was read as a reference to the current object, so it printed that object's ToString() (HTML-encoded). The text after it stayed in the main block, and the block had no inverse branch. After the fix, {{^}} splits the block the same way {{else}} does.

    The stray-{{^}} row is the only case where output that used to be non-empty changes for a template that isn't using {{^}} as a separator. The old output was the context object's ToString(), which seems unlikely to be anything people rely on.

    Status is unchanged: the fix is on branch claude/issue-672 and has not been shipped.

  7. rexm commented on Nov 7, 2026

    @rexm
    Member

    Cases 2,4,6 may reflect a bug some customers are implicitly relying on. Add a configuration option with a default to the new correct behavior that allows customers to revert to the old buggy behavior, then ship a PR.

    /harness ship

  8. stencil-harness commented on Nov 7, 2026

    @stencil-harness
    Contributor

    Added the opt-out and opened #675. Auto-merge is requested, so GitHub will merge it once the required checks pass.

    What changed (Handlebars-Net/Handlebars.Net):

    • New setting Compatibility.LegacyStandaloneCaretBehavior, default false. By default {{^}} now behaves like {{else}}. Setting the option to true skips the new step completely, so every case in the earlier table goes back to its old output. That includes 2, 4 and 6, which render empty again. {{else}} behaves the same with either setting.
    • The setting is documented in the README under "Compatibility feature toggles", with an example.
    • New tests check that the flag restores the old output for #if, #each and sections, that {{else}} is unaffected, and that the flag defaults to false.

    Verification: the full test suite passes (2185 tests, 0 failures). The library builds for netstandard2.0, netstandard2.1, net8.0 and net10.0.

    Shipped: Handlebars.Net, through PR #675 (auto-merge requested). No other repos changed. No release has been created.

  9. rexm commented on Nov 7, 2026

    @rexm
    Member

    Open a new issue for the raw block bug

  10. stencil-harness commented on Nov 7, 2026

    @stencil-harness
    Contributor

    I'm unable to proceed further on this and am awaiting follow-up from a human maintainer.

  11. stencil-harness commented on Nov 7, 2026

    @stencil-harness
    Contributor

    I opened #676 for the raw block bug: with Compatibility.RelaxedHelperNaming = true, raw block helpers fail to compile. The issue includes a minimal reproduction, a likely cause in HelperConverter.IsUnregisteredBlockHelperName (it never skips closing tags) and a suggested fix.

    I didn't change any code for this request. PR #675 for this issue is unchanged.

  12. added a commit that references this issue on Nov 7, 2026
    8e2fee6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions