Skip to content

{{#if}} / {{#unless}} without an argument throw InvalidOperationException: Sequence contains no elements #674

Closed

Description

@hidingmyname

Describe the bug

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

        private static (Expression Value, HashParametersExpression HashParameters) UnwrapBoolishHelperArguments(IEnumerable<Expression> arguments, IReaderContext? context)
        {
            var value = arguments.First();
            if (arguments.Count() == 1)
            {
                var blankHashParameters = HandlebarsExpression.HashParametersExpression(new Dictionary<string, Expression>());
                return (value, blankHashParameters);
            }

            if (arguments.Count() == 2 && arguments.Last() is HashParametersExpression hashParameters)
            {
                return (value, hashParameters);
            }

            throw new HandlebarsCompilerException("Invalid argument list for conditional block.", context);

        }

Problem

Handlebars.Compile("{{#if}}yes{{/if}}") (same for {{#unless}}) fails with a bare System.InvalidOperationException: Sequence contains no elements thrown by Enumerable.First, not with a HandlebarsCompilerException. Code that catches HandlebarsException to report template errors does not catch it, and the message gives no hint about the template, the helper or the location.

With too many arguments ({{#if a b}}) a HandlebarsCompilerException is already thrown, but its message Invalid argument list for conditional block. does not say which helper or what is expected.

Both cases fail at compile time; this is only about the exception type and message.

Expected behavior:

{{#if}}, {{#unless}}, {{#if a b}} and {{#unless a b}} throw HandlebarsCompilerException (with the reader context) and a message such as #if requires exactly one argument / #unless requires exactly one argument. {{#if a includeZero=true}} keeps working.

Test to reproduce

[Theory]
[InlineData("{{#if}}yes{{/if}}", "#if")]
[InlineData("{{#unless}}yes{{/unless}}", "#unless")]
[InlineData("{{#if a b}}yes{{/if}}", "#if")]
[InlineData("{{#unless a b}}yes{{/unless}}", "#unless")]
public void TestConditionalBlockWithWrongArgumentCountException(string source, string helper)
{
    var exception = Assert.Throws<HandlebarsCompilerException>(() =>
    {
        Handlebars.Compile(source);
    });

    Assert.Contains($"{helper} requires exactly one argument", exception.Message);
}

Run from source/: dotnet test Handlebars.Test/Handlebars.Test.csproj --filter "FullyQualifiedName~TestConditionalBlockWithWrongArgumentCountException":

  Failed HandlebarsDotNet.Test.ExceptionTests.TestConditionalBlockWithWrongArgumentCountException(source: "{{#if}}yes{{/if}}", helper: "#if") [1 ms]
  Error Message:
   Assert.Throws() Failure: Exception type was not an exact match
Expected: typeof(HandlebarsDotNet.HandlebarsCompilerException)
Actual:   typeof(System.InvalidOperationException)
---- System.InvalidOperationException : Sequence contains no elements
...
----- Inner Stack Trace -----
   at System.Linq.ThrowHelper.ThrowNoElementsException()
   at System.Linq.Enumerable.First[TSource](IEnumerable`1 source)
   at HandlebarsDotNet.Compiler.ConditionalBlockAccumulatorContext.UnwrapBoolishHelperArguments(IEnumerable`1 arguments, IReaderContext context) in .../source/Handlebars/Compiler/Lexer/Converter/BlockAccumulators/ConditionalBlockAccumulatorContext.cs:line 149
   at HandlebarsDotNet.Compiler.ConditionalBlockAccumulatorContext..ctor(Expression startingNode) in .../source/Handlebars/Compiler/Lexer/Converter/BlockAccumulators/ConditionalBlockAccumulatorContext.cs:line 37
...
  Failed HandlebarsDotNet.Test.ExceptionTests.TestConditionalBlockWithWrongArgumentCountException(source: "{{#if a b}}yes{{/if}}", helper: "#if") [< 1 ms]
  Error Message:
   Assert.Contains() Failure: Sub-string not found
String:    "Invalid argument list for conditional blo"···
Not found: "#if requires exactly one argument"
...
Failed!  - Failed:     4, Passed:     0, Skipped:     0, Total:     4, Duration: 403 ms - Handlebars.Test.dll (net10.0)

({{#unless}} and {{#unless a b}} fail the same way.)

Environment:

  • Commit: c9a20a29529a; the file is 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#1549 — "fix: add guard to if & unless helpers" (merged 2019-10-27T14:41:36Z, merge commit c76ded8f0f1). It makes if, unless (and with) throw #if requires exactly one argument etc. when the argument count is wrong.

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

--- a/lib/handlebars/helpers/if.js
+++ b/lib/handlebars/helpers/if.js
@@ -1,7 +1,9 @@
-import {isEmpty, isFunction} from '../utils';
+import { isEmpty, isFunction } from '../utils';
+import Exception from '../exception';
 
 export default function(instance) {
   instance.registerHelper('if', function(conditional, options) {
+    if (arguments.length != 2) { throw new Exception('#if requires exactly one argument');}
     if (isFunction(conditional)) { conditional = conditional.call(this); }
 
     // Default behavior is to render the positive path if the value is truthy and not empty.
@@ -15,6 +17,7 @@ export default function(instance) {
   });
 
   instance.registerHelper('unless', function(conditional, options) {
+    if (arguments.length != 2) { throw new Exception('#unless requires exactly one argument');}
     return instance.helpers['if'].call(this, conditional, {fn: options.inverse, inverse: options.fn, hash: options.hash});
   });
 }

Suggested fix

Check for a missing argument before calling First() and use the same helper-specific message for both wrong-count cases:

diff --git a/source/Handlebars/Compiler/Lexer/Converter/BlockAccumulators/ConditionalBlockAccumulatorContext.cs b/source/Handlebars/Compiler/Lexer/Converter/BlockAccumulators/ConditionalBlockAccumulatorContext.cs
--- a/source/Handlebars/Compiler/Lexer/Converter/BlockAccumulators/ConditionalBlockAccumulatorContext.cs
+++ b/source/Handlebars/Compiler/Lexer/Converter/BlockAccumulators/ConditionalBlockAccumulatorContext.cs
@@ -34,7 +34,7 @@ namespace HandlebarsDotNet.Compiler
                 throw new HandlebarsCompilerException($"Tried to convert {BlockName} expression to conditional block", helperExpression.Context);
             }
 
-            var (value, hashParameters) = UnwrapBoolishHelperArguments(helperExpression.Arguments, helperExpression.Context);
+            var (value, hashParameters) = UnwrapBoolishHelperArguments(BlockName, helperExpression.Arguments, helperExpression.Context);
             var argument = HandlebarsExpression.Boolish(value, hashParameters);
 
             _currentCondition = BlockName switch
@@ -124,7 +124,7 @@ namespace HandlebarsDotNet.Compiler
         {
             item = UnwrapStatement(item);
             var helperExpression = (HelperExpression)item;
-            var (value, hashParameters) = UnwrapBoolishHelperArguments(helperExpression.Arguments.Skip(1), helperExpression.Context);
+            var (value, hashParameters) = UnwrapBoolishHelperArguments(BlockName, helperExpression.Arguments.Skip(1), helperExpression.Context);
             return HandlebarsExpression.Boolish(value, hashParameters);
         }
 
@@ -144,9 +144,10 @@ namespace HandlebarsDotNet.Compiler
             return expressions.SingleOrDefault() ?? Expression.Empty();
         }
 
-        private static (Expression Value, HashParametersExpression HashParameters) UnwrapBoolishHelperArguments(IEnumerable<Expression> arguments, IReaderContext? context)
+        private static (Expression Value, HashParametersExpression HashParameters) UnwrapBoolishHelperArguments(string blockName, IEnumerable<Expression> arguments, IReaderContext? context)
         {
-            var value = arguments.First();
+            var value = arguments.FirstOrDefault()
+                ?? throw new HandlebarsCompilerException($"#{blockName} requires exactly one argument", context);
             if (arguments.Count() == 1)
             {
                 var blankHashParameters = HandlebarsExpression.HashParametersExpression(new Dictionary<string, Expression>());
@@ -158,7 +159,7 @@ namespace HandlebarsDotNet.Compiler
                 return (value, hashParameters);
             }
 
-            throw new HandlebarsCompilerException("Invalid argument list for conditional block.", context);
+            throw new HandlebarsCompilerException($"#{blockName} requires exactly one argument", context);
 
         }
     }

Verified on c9a20a2 (.NET SDK 10.0.403, net10.0): the test above fails without this patch and passes with it; no other test results change (dotnet test Handlebars.Test/Handlebars.Test.csproj).

I can submit a PR for this.

Checked: #202 and #224 ("Sequence contains no elements" for empty block bodies) were a different, already fixed problem; #639 adds hash-argument support to #if. No issue covers a missing #if / #unless argument.

Activity

  1. rexm commented on Nov 7, 2026

    @rexm
    Member

    /harness adopt

  2. stencil-harness commented on Nov 7, 2026

    @stencil-harness
    Contributor

    I'm the agent managing intake of issues on Rex's behalf. I understand the request: {{#if}} / {{#unless}} with no argument (or too many) should throw a HandlebarsCompilerException with a helper-specific message instead of a bare InvalidOperationException. I'll evaluate whether I can address this autonomously.

  3. stencil-harness commented on Nov 7, 2026

    @stencil-harness
    Contributor

    Fix staged on branch claude/issue-674 (not merged or released).

    Handlebars.Net — what changed

    • ConditionalBlockAccumulatorContext: {{#if}} / {{#unless}} (and {{^if}}) with no argument now throw HandlebarsCompilerException with the reader context, not InvalidOperationException: Sequence contains no elements.
    • The message for too many arguments ({{#if a b}}) also changes. It was Invalid argument list for conditional block. and is now #if requires exactly one argument / #unless requires exactly one argument, the same wording handlebars.js uses. The exception type stays the same.
    • {{#if a includeZero=true}} still works.

    Compatibility note: both cases already failed at compile time, so templates that compiled before still compile and render the same way. Callers will see a change in two places: the no-argument case now throws HandlebarsCompilerException instead of InvalidOperationException, and the too-many-arguments message text is different.

    How I verified it

    • Added tests to ExceptionTests: the four cases from the issue plus {{^if}}, and a check that hash arguments still compile for #if and #unless.
    • The full Handlebars.Test suite passes (2200/2200).
  4. rexm commented on Nov 7, 2026

    @rexm
    Member

    /harness ship

  5. stencil-harness commented on Nov 7, 2026

    @stencil-harness
    Contributor

    I opened #678 for the Handlebars.Net fix. Auto-merge is on, so GitHub will merge it into master once the required checks pass.

    • What changed: In Handlebars.Net, {{#if}} / {{#unless}} with no argument now throw HandlebarsCompilerException instead of InvalidOperationException. Both the no-argument and too-many-arguments cases now use the message #if requires exactly one argument / #unless requires exactly one argument. Nothing else changed.
    • Verified: The branch already includes the latest master. I ran the full Handlebars.Test suite again right before opening the PR and all 2200 tests passed.
    • Shipped: The PR merges into master once checks pass. No NuGet release has been cut; that is a separate step.
  6. added a commit that references this issue on Nov 25, 2026
    9c3f75b
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