Repository navigation
Description
Describe the bug
Location (Handlebars-Net/Handlebars.Net @ c9a20a2):
source/Handlebars/Compiler/Lexer/Parsers/BlockWordParser.cs:29-58:{{^}}is read as the word^(the caret followed directly by}}).source/Handlebars/Compiler/Lexer/Converter/HelperConverter.cs:45-69:{{else}}becomes theelsehelper expression, but the word^matches none of the cases and falls through todefault, so it later becomes a path expression.source/Handlebars/Compiler/Lexer/Converter/BlockAccumulators/ConditionalBlockAccumulatorContext.cs:111-115(and the same check inBlockHelperAccumulatorContext/IteratorBlockAccumulatorContext): only a helper namedelsesplits the block.
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}}withcondition = truerendersyes{ condition = True }noinstead ofyes.{{#each people}}{{name}}{{^}}No one{{/each}}rendersAlice{ name = Alice }No onefor one person.- For a falsy section (
{{#val}}yes{{^}}no{{/val}},val = false) there is no inverse block, so the output is empty instead ofno.
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 = 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 = 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 = 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 currentmaster(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
rexm commentedon Nov 7, 2026
Nudging my helperbot to take a look at this
/harness adopt
stencil-harness commentedon Nov 7, 2026
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.stencil-harness commentedon Nov 7, 2026
I'm unable to proceed further on this and am awaiting follow-up from a human maintainer.
stencil-harness commentedon Nov 7, 2026
A standalone
{{^}}now works as the inverse separator, exactly like{{else}}. The fix is on branchclaude/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):
{{^}},{{^ }}or{{~^~}}is now treated as the sameelsemarker that{{else}}produces. This works in#if,#unless,#each,#with, sections and custom block helpers.InverseSeparatorConverter. It runs after raw blocks are processed, so{{^}}inside{{{{raw}}}}...{{{{/raw}}}}stays literal text. Putting it inHelperConverter, as the issue suggested, would have made it render as{{else}}inside raw blocks.InvertedSection_InlineCaretSyntaxnow expectsyes/no. New tests cover each block type, the whitespace and~forms, a tag on its own line, and raw blocks. "Gap 5" is removed fromHandlebarsSpec.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'sToString().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.rexm commentedon Nov 7, 2026
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.
stencil-harness commentedon Nov 7, 2026
What "45 of 46 fail" means
The new tests make up 46 test cases:
HandlebarsEnvGenerator), giving 45 cases:InvertedSection_InlineCaretSyntax...InListSection,...InIf,...InUnless,...InEach,...InWith,...InCustomBlockHelper...WithWhitespace,...StandaloneLineInvertedSection_InlineCaretSyntaxIsLiteralInsideRawBlock, makes 46.I removed the one line that runs
InverseSeparatorConverterinExpressionBuilderand 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)
{{#if condition}}yes{{^}}no{{/if}}condition = trueyes{ condition = True }noyes{{#if condition}}yes{{^}}no{{/if}}condition = falseno{{#each people}}{{name}}{{^}}No one{{/each}}Alice{ name = Alice }No oneAlice{{#each people}}{{name}}{{^}}No one{{/each}}No one{{#val}}yes{{^}}no{{/val}}val = trueyes{ val = True }noyes{{#val}}yes{{^}}no{{/val}}val = falsenoa{{^}}b(stray, outside any block)x = 1a{ x = 1 }bab(same as a stray{{else}}){{{{raw}}}}a{{^}}b{{{{/raw}}}}a{{^}}ba{{^}}b(unchanged)Before the fix,
{{^}}was read as a reference to the current object, so it printed that object'sToString()(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'sToString(), which seems unlikely to be anything people rely on.Status is unchanged: the fix is on branch
claude/issue-672and has not been shipped.rexm commentedon Nov 7, 2026
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
feat: add Compatibility.LegacyStandaloneCaretBehavior opt-out
stencil-harness commentedon Nov 7, 2026
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):
Compatibility.LegacyStandaloneCaretBehavior, defaultfalse. By default{{^}}now behaves like{{else}}. Setting the option totrueskips 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.#if,#eachand sections, that{{else}}is unaffected, and that the flag defaults tofalse.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.
rexm commentedon Nov 7, 2026
Open a new issue for the raw block bug
stencil-harness commentedon Nov 7, 2026
I'm unable to proceed further on this and am awaiting follow-up from a human maintainer.
stencil-harness commentedon Nov 7, 2026
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 inHelperConverter.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.
fix: treat standalone {{^}} as the inverse separator, like {{else}}