diff --git a/README.md b/README.md index edd22bfe..144b4daa 100644 --- a/README.md +++ b/README.md @@ -490,6 +490,35 @@ public void LegacyInlinePartialScoping() } ``` +#### `LegacyBareElseNameBehavior` +By default a bare `{{else name}}` (nothing after the name) inside `{{#if}}` / `{{#unless}}` follows Handlebarsjs: it is equivalent to `{{else}}{{#name}}…{{/name}}`. A block helper `name` is invoked; otherwise `name` is resolved as a value, so the branch renders only when it is truthy, and iterates when it is a list. A bare `{{else if}}` / `{{else unless}}` with no condition throws `HandlebarsCompilerException` (`#if requires exactly one argument`). +If `true`, restores the earlier Handlebars.Net behavior where the name is ignored and the branch renders as a plain `{{else}}`. +Bare `{{else name}}` under other blocks (`{{#each}}`, custom block helpers) is not affected. Use only as a temporary escape hatch; the long-term fix is usually the missing `if` (`{{else if name}}`) or a plain `{{else}}`. + +| Template | Data | Default | `LegacyBareElseNameBehavior = true` | +|---|---|---|---| +| `{{#if a}}A{{else isAdmin}}B{{/if}}` | `a = false, isAdmin = false` | *(empty)* | `B` | +| `{{#if a}}A{{else items}}[{{this}}]{{/if}}` | `a = false, items = [1, 2]` | `[1][2]` | `[` + the outer context + `]` | +| `{{#if a}}A{{else if}}B{{/if}}` | `a = false` | `HandlebarsCompilerException` | `B` | + +##### Areas +- `Compile-time` + +##### Example +```c# +[Fact] +public void LegacyBareElseName() +{ + var handlebars = Handlebars.Create(); + handlebars.Configuration.Compatibility.LegacyBareElseNameBehavior = true; + + var template = handlebars.Compile("{{#if user.isAdmin}}Admin tools{{else user.isModerator}}Moderator tools{{/if}}"); + + var user = new { isAdmin = false, isModerator = false }; + Assert.Equal("Moderator tools", template(new { user })); // "" with the default behavior +} +``` + #### HtmlEncoder Used to switch between the legacy Handlebars.Net and the canonical Handlebars rules (or a custom implementation).\ For Handlebars.Net 2.x.x `HtmlEncoderLegacy` is the default. diff --git a/source/Handlebars.Test/ConditionalElseChainTests.cs b/source/Handlebars.Test/ConditionalElseChainTests.cs index 7540130f..871cfc9a 100644 --- a/source/Handlebars.Test/ConditionalElseChainTests.cs +++ b/source/Handlebars.Test/ConditionalElseChainTests.cs @@ -128,18 +128,147 @@ public void ElseAfterPlainElseIsACompilerError() handlebars.Compile("{{#if a}}A{{else}}B{{else}}C{{/if}}")); } - // A bare name after "else" (including a condition-less "{{else if}}") has always rendered as - // a plain "{{else}}"; that is kept so existing templates keep compiling. + // A bare "{{else name}}" follows handlebars.js: it is "{{else}}{{#name}}...{{/name}}". + // https://github.com/Handlebars-Net/Handlebars.Net/issues/695 [Theory] - [InlineData("{{#if a}}A{{else ifNot}}B{{/if}}")] - [InlineData("{{#if a}}A{{else if}}B{{/if}}")] - [InlineData("{{#if a}}A{{else unless}}B{{/if}}")] - public void ElseWithOnlyANameStillRendersAsPlainElse(string source) + [InlineData("{{#if a}}A{{else b}}B{{/if}}", true, false, true, "A")] + [InlineData("{{#if a}}A{{else b}}B{{/if}}", false, false, true, "B")] + [InlineData("{{#if a}}A{{else b}}B{{/if}}", false, false, false, "")] + [InlineData("{{#unless a}}A{{else b}}B{{/unless}}", false, false, true, "A")] + [InlineData("{{#unless a}}A{{else b}}B{{/unless}}", true, false, true, "B")] + [InlineData("{{#unless a}}A{{else b}}B{{/unless}}", true, false, false, "")] + [InlineData("{{#if a}}A{{else b}}B{{else}}C{{/if}}", false, false, false, "C")] + [InlineData("{{#if a}}A{{else b}}B{{/if}}", false, true, false, "B")] + [InlineData("{{#unless a}}A{{else b}}B{{/unless}}", true, true, false, "B")] + public void BareElseNameIsResolvedAsAValue(string source, bool a, bool legacy, bool b, string expected) { - var template = CreateWithHelpers().Compile(source); + var handlebars = CreateWithHelpers(); + handlebars.Configuration.Compatibility.LegacyBareElseNameBehavior = legacy; + var template = handlebars.Compile(source); + + Assert.Equal(expected, template(new { a, b })); + } + + [Theory] + [InlineData("{{#if a}}A{{else items}}[{{this}}]{{/if}}", false, "[1][2]")] + [InlineData("{{#unless a}}A{{else items}}[{{this}}]{{/unless}}", false, "[1][2]")] + [InlineData("{{#if a}}A{{else items}}[{{x}}]{{/if}}", true, "[outer]")] + [InlineData("{{#unless a}}A{{else items}}[{{x}}]{{/unless}}", true, "[outer]")] + public void BareElseNameIteratesAList(string source, bool legacy, string expected) + { + var handlebars = CreateWithHelpers(); + handlebars.Configuration.Compatibility.LegacyBareElseNameBehavior = legacy; + var template = handlebars.Compile(source); + + var a = source.StartsWith("{{#unless"); + Assert.Equal(expected, template(new { a, items = new[] { 1, 2 }, x = "outer" })); + } + + [Theory] + [InlineData(false, "B")] + [InlineData(true, "B")] + public void BareElseNameInvokesARegisteredBlockHelper(bool legacy, string expected) + { + var handlebars = Handlebars.Create(); + handlebars.Configuration.Compatibility.LegacyBareElseNameBehavior = legacy; + var invoked = false; + handlebars.RegisterHelper("track", (output, options, context, arguments) => + { + invoked = true; + options.Template(output, context); + }); + var template = handlebars.Compile("{{#if a}}A{{else track}}B{{/if}}"); + + Assert.Equal(expected, template(new { a = false })); + Assert.Equal(!legacy, invoked); + } + + [Theory] + [InlineData("{{#if a}}A{{else if}}B{{/if}}", "if")] + [InlineData("{{#if a}}A{{else unless}}B{{/if}}", "unless")] + [InlineData("{{#unless a}}A{{else if}}B{{/unless}}", "if")] + [InlineData("{{#unless a}}A{{else unless}}B{{/unless}}", "unless")] + public void ConditionlessElseIfIsACompilerError(string source, string keyword) + { + var handlebars = CreateWithHelpers(); + + var exception = Assert.Throws(() => handlebars.Compile(source)); + Assert.Contains($"#{keyword} requires exactly one argument", exception.Message); + Assert.Contains($"'{{{{else {keyword}}}}}'", exception.Message); + Assert.Contains("Configuration.Compatibility.LegacyBareElseNameBehavior = true", exception.Message); + } + + // With the opt-out, a bare name after "else" (including a condition-less "{{else if}}") + // renders as a plain "{{else}}", as in earlier Handlebars.Net versions. + [Theory] + [InlineData("{{#if a}}A{{else ifNot}}B{{/if}}", true, false)] + [InlineData("{{#if a}}A{{else if}}B{{/if}}", true, false)] + [InlineData("{{#if a}}A{{else unless}}B{{/if}}", true, false)] + [InlineData("{{#unless a}}A{{else if}}B{{/unless}}", false, true)] + [InlineData("{{#unless a}}A{{else unless}}B{{/unless}}", false, true)] + public void LegacyBareElseNameRendersAsPlainElse(string source, bool showsA, bool showsB) + { + var handlebars = CreateWithHelpers(); + handlebars.Configuration.Compatibility.LegacyBareElseNameBehavior = true; + var template = handlebars.Compile(source); + + Assert.Equal("A", template(new { a = showsA })); + Assert.Equal("B", template(new { a = showsB })); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void ElseAfterPlainElseIsACompilerErrorForBareNames(bool legacy) + { + var handlebars = CreateWithHelpers(); + handlebars.Configuration.Compatibility.LegacyBareElseNameBehavior = legacy; + + Assert.Throws(() => + handlebars.Compile("{{#if a}}A{{else}}B{{else b}}C{{/if}}")); + } + + // Realistic case from https://github.com/Handlebars-Net/Handlebars.Net/issues/695: the "if" was left out. + [Theory] + [InlineData(false, false, false, "")] + [InlineData(false, false, true, "Moderator tools")] + [InlineData(true, false, false, "Moderator tools")] + [InlineData(false, true, false, "Admin tools")] + public void MissingIfAfterElseOnlyRendersForTruthyName(bool legacy, bool isAdmin, bool isModerator, string expected) + { + var handlebars = Handlebars.Create(); + handlebars.Configuration.Compatibility.LegacyBareElseNameBehavior = legacy; + var template = handlebars.Compile("{{#if user.isAdmin}}Admin tools{{else user.isModerator}}Moderator tools{{/if}}"); + + Assert.Equal(expected, template(new { user = new { isAdmin, isModerator } })); + } + + // Under non-conditional blocks a bare "{{else name}}" desugars in both modes. + [Theory] + [InlineData(false)] + [InlineData(true)] + public void BareElseNameUnderEachIsUnaffectedByLegacyFlag(bool legacy) + { + var handlebars = Handlebars.Create(); + handlebars.Configuration.Compatibility.LegacyBareElseNameBehavior = legacy; + var template = handlebars.Compile("{{#each list}}x{{else b}}B{{/each}}"); + + Assert.Equal("B", template(new { list = new int[0], b = true })); + Assert.Equal("", template(new { list = new int[0], b = false })); + } + + // A non-path first argument keeps the earlier "else if" on the remaining arguments in both modes. + [Theory] + [InlineData(false)] + [InlineData(true)] + public void NonPathElseNameIsUnaffectedByLegacyFlag(bool legacy) + { + var handlebars = Handlebars.Create(); + handlebars.Configuration.Compatibility.LegacyBareElseNameBehavior = legacy; + var template = handlebars.Compile("{{#if a}}A{{else \"x\" b}}B{{else}}C{{/if}}"); - Assert.Equal("A", template(new { a = true })); - Assert.Equal("B", template(new { a = false })); + Assert.Equal("B", template(new { a = false, b = true })); + Assert.Equal("C", template(new { a = false, b = false })); } // Case contributed in https://github.com/Handlebars-Net/Handlebars.Net/pull/684 diff --git a/source/Handlebars.Test/ExceptionTests.cs b/source/Handlebars.Test/ExceptionTests.cs index d8f220ba..458ad450 100644 --- a/source/Handlebars.Test/ExceptionTests.cs +++ b/source/Handlebars.Test/ExceptionTests.cs @@ -80,6 +80,22 @@ public void TestConditionalBlockWithWrongArgumentCountException(string source, s Assert.Contains($"{helper} requires exactly one argument", exception.Message); } + // A bare "{{else if}}" / "{{else unless}}" is an error, and the message names the opt-out. + // https://github.com/Handlebars-Net/Handlebars.Net/issues/695 + [Theory] + [InlineData("{{#if a}}yes{{else if}}no{{/if}}", "if")] + [InlineData("{{#if a}}yes{{else unless}}no{{/if}}", "unless")] + [InlineData("{{#unless a}}yes{{else if}}no{{/unless}}", "if")] + [InlineData("{{#unless a}}yes{{else unless}}no{{/unless}}", "unless")] + public void TestConditionlessElseIfExceptionNamesOptOut(string source, string keyword) + { + var exception = Assert.Throws(() => Handlebars.Compile(source)); + + Assert.Contains( + $"#{keyword} requires exactly one argument. To restore the previous behavior, where a bare '{{{{else {keyword}}}}}' rendered as '{{{{else}}}}', set Configuration.Compatibility.LegacyBareElseNameBehavior = true", + exception.Message); + } + [Theory] [InlineData("{{#if a includeZero=true}}yes{{else}}no{{/if}}", "yes")] [InlineData("{{#unless a includeZero=true}}yes{{else}}no{{/unless}}", "no")] diff --git a/source/Handlebars/Compiler/Lexer/Converter/BlockAccumulators/BlockAccumulatorContext.cs b/source/Handlebars/Compiler/Lexer/Converter/BlockAccumulators/BlockAccumulatorContext.cs index bdefc763..0b6ae8e1 100644 --- a/source/Handlebars/Compiler/Lexer/Converter/BlockAccumulators/BlockAccumulatorContext.cs +++ b/source/Handlebars/Compiler/Lexer/Converter/BlockAccumulators/BlockAccumulatorContext.cs @@ -18,7 +18,7 @@ internal abstract class BlockAccumulatorContext BlockAccumulatorContext? context = null; if (IsConditionalBlock(item)) { - context = new ConditionalBlockAccumulatorContext(item); + context = new ConditionalBlockAccumulatorContext(item, configuration.Compatibility.LegacyBareElseNameBehavior); } else if (IsPartialBlock(item)) { diff --git a/source/Handlebars/Compiler/Lexer/Converter/BlockAccumulators/ConditionalBlockAccumulatorContext.cs b/source/Handlebars/Compiler/Lexer/Converter/BlockAccumulators/ConditionalBlockAccumulatorContext.cs index 316592b8..841d9346 100644 --- a/source/Handlebars/Compiler/Lexer/Converter/BlockAccumulators/ConditionalBlockAccumulatorContext.cs +++ b/source/Handlebars/Compiler/Lexer/Converter/BlockAccumulators/ConditionalBlockAccumulatorContext.cs @@ -19,11 +19,15 @@ private enum TestType { Direct, Reverse } private bool _finalBranchClosed; + private readonly bool _legacyBareElseName; + /// /// "{{else if x}}" is resolved into a flat chain of conditions below, so it must not also be /// desugared into a nested block by . Any other named chain - /// ("{{else unless x}}", "{{else customHelper a b}}") is left to that generic desugaring, - /// which nests the named block helper inside this block's inverse, as handlebars.js does. + /// ("{{else unless x}}", "{{else customHelper a b}}", and a bare "{{else name}}") is left to that + /// generic desugaring, which nests the named block helper inside this block's inverse, as handlebars.js does. + /// With a bare "{{else name}}" is kept here + /// and renders as a plain "{{else}}". /// internal override bool HandlesChainedElseInternally(Expression elseItem) { @@ -31,17 +35,19 @@ internal override bool HandlesChainedElseInternally(Expression elseItem) using var arguments = helperExpression.Arguments.GetEnumerator(); if (!arguments.MoveNext()) return true; - var first = arguments.Current; + // A non-path first argument ("{{else "x" b}}") keeps the earlier "else if" on the remaining arguments. + if (!(arguments.Current is PathExpression path)) return true; - // "{{else name}}" with nothing after the name has always rendered as a plain "{{else}}". - if (!arguments.MoveNext()) return true; + if (string.Equals(path.Path, "if", StringComparison.OrdinalIgnoreCase)) return true; - return !(first is PathExpression path) || string.Equals(path.Path, "if", StringComparison.OrdinalIgnoreCase); + // "{{else name}}" with nothing after the name renders as a plain "{{else}}" in legacy mode. + return _legacyBareElseName && !arguments.MoveNext(); } - public ConditionalBlockAccumulatorContext(Expression startingNode) + public ConditionalBlockAccumulatorContext(Expression startingNode, bool legacyBareElseName = false) : base(startingNode) { + _legacyBareElseName = legacyBareElseName; startingNode = UnwrapStatement(startingNode); var helperExpression = (HelperExpression)startingNode; var testType = helperExpression.HelperName[0] == '#' ? TestType.Direct : TestType.Reverse; @@ -79,6 +85,8 @@ public override void HandleElement(Expression item) throw new HandlebarsCompilerException(message, GetReaderContext(item)); } + if (!_legacyBareElseName) ThrowIfConditionlessElseIf(item); + _conditionalBlock.Add(Expression.IfThen(_currentCondition, SinglifyExpressions(_bodyBuffer))); if (IsElseIfBlock(item)) { @@ -152,6 +160,24 @@ private bool IsElseIfBlock(Expression item) && HandlesChainedElseInternally(item); } + /// + /// A bare "{{else if}}" / "{{else unless}}" has no condition. handlebars.js rejects it; + /// earlier Handlebars.Net versions rendered it as a plain "{{else}}". + /// + private static void ThrowIfConditionlessElseIf(Expression item) + { + var helperExpression = (HelperExpression)UnwrapStatement(item); + using var arguments = helperExpression.Arguments.GetEnumerator(); + if (!arguments.MoveNext() || !(arguments.Current is PathExpression path) || arguments.MoveNext()) return; + + if (!ValidHelperNames.Contains(path.Path.ToLowerInvariant())) return; + + throw new HandlebarsCompilerException( + $"#{path.Path} requires exactly one argument. To restore the previous behavior, where a bare '{{{{else {path.Path}}}}}' rendered as '{{{{else}}}}', " + + $"set Configuration.Compatibility.{nameof(Compatibility.LegacyBareElseNameBehavior)} = true", + helperExpression.Context); + } + private Expression GetElseIfTestExpression(Expression item) { item = UnwrapStatement(item); diff --git a/source/Handlebars/Configuration/Compatibility.cs b/source/Handlebars/Configuration/Compatibility.cs index 2659edba..4f1c24f5 100644 --- a/source/Handlebars/Configuration/Compatibility.cs +++ b/source/Handlebars/Configuration/Compatibility.cs @@ -44,5 +44,18 @@ public class Compatibility /// Setting it to is intended only as a temporary escape hatch for templates that depend on the old behavior. /// public bool BlockScopedInlinePartials { get; set; } = true; + + /// + /// If restores the earlier Handlebars.Net handling of a bare {{else name}} + /// (nothing after the name) inside {{#if}} / {{#unless}}. + /// By default () it follows Handlebarsjs: {{else name}} is equivalent to + /// {{else}}{{#name}}…{{/name}}, so a block helper name is invoked, or else name is resolved as a value: + /// {{#if a}}A{{else b}}B{{/if}} renders B only when a is falsy and b is truthy, and iterates when + /// b is a list. A bare {{else if}} / {{else unless}} with no condition is a . + /// When , the name is ignored and the branch renders as a plain {{else}}: + /// the template above renders B whenever a is falsy. + /// Read at compile time. Intended only as a temporary escape hatch for templates that depend on the old behavior. + /// + public bool LegacyBareElseNameBehavior { get; set; } = false; } }