Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
147 changes: 138 additions & 9 deletions source/Handlebars.Test/ConditionalElseChainTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -128,18 +128,147 @@
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" }));

Check warning on line 164 in source/Handlebars.Test/ConditionalElseChainTests.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Prefer 'static readonly' fields over constant array arguments if the called method is called repeatedly and is not mutating the passed array

See more on https://sonarcloud.io/project/issues?id=Handlebars-Net_Handlebars.Net&issues=AaIEvkFCxLZqvao8T-1T&open=AaIEvkFCxLZqvao8T-1T&pullRequest=696
}

[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<HandlebarsCompilerException>(() => 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<HandlebarsCompilerException>(() =>
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 }));

Check warning on line 256 in source/Handlebars.Test/ConditionalElseChainTests.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Avoid unnecessary zero-length array allocations. Use Array.Empty<int>() instead.

See more on https://sonarcloud.io/project/issues?id=Handlebars-Net_Handlebars.Net&issues=AaIEvkFCxLZqvao8T-1U&open=AaIEvkFCxLZqvao8T-1U&pullRequest=696
Assert.Equal("", template(new { list = new int[0], b = false }));

Check warning on line 257 in source/Handlebars.Test/ConditionalElseChainTests.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Avoid unnecessary zero-length array allocations. Use Array.Empty<int>() instead.

See more on https://sonarcloud.io/project/issues?id=Handlebars-Net_Handlebars.Net&issues=AaIEvkFCxLZqvao8T-1V&open=AaIEvkFCxLZqvao8T-1V&pullRequest=696
}

// 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
Expand Down
16 changes: 16 additions & 0 deletions source/Handlebars.Test/ExceptionTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<HandlebarsCompilerException>(() => 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")]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,29 +19,35 @@ private enum TestType { Direct, Reverse }

private bool _finalBranchClosed;

private readonly bool _legacyBareElseName;

/// <summary>
/// "{{else if x}}" is resolved into a flat chain of conditions below, so it must not also be
/// desugared into a nested block by <see cref="BlockAccumulator"/>. 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 <see cref="Compatibility.LegacyBareElseNameBehavior"/> a bare "{{else name}}" is kept here
/// and renders as a plain "{{else}}".
/// </summary>
internal override bool HandlesChainedElseInternally(Expression elseItem)
{
var helperExpression = (HelperExpression)UnwrapStatement(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;
Expand Down Expand Up @@ -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))
{
Expand Down Expand Up @@ -152,6 +160,24 @@ private bool IsElseIfBlock(Expression item)
&& HandlesChainedElseInternally(item);
}

/// <summary>
/// A bare "{{else if}}" / "{{else unless}}" has no condition. handlebars.js rejects it;
/// earlier Handlebars.Net versions rendered it as a plain "{{else}}".
/// </summary>
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);
Expand Down
13 changes: 13 additions & 0 deletions source/Handlebars/Configuration/Compatibility.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,5 +44,18 @@ public class Compatibility
/// <para>Setting it to <see langword="false"/> is intended only as a temporary escape hatch for templates that depend on the old behavior.</para>
/// </summary>
public bool BlockScopedInlinePartials { get; set; } = true;

/// <summary>
/// If <see langword="true"/> restores the earlier Handlebars.Net handling of a bare <c>{{else name}}</c>
/// (nothing after the name) inside <c>{{#if}}</c> / <c>{{#unless}}</c>.
/// <para>By default (<see langword="false"/>) it follows Handlebarsjs: <c>{{else name}}</c> is equivalent to
/// <c>{{else}}{{#name}}…{{/name}}</c>, so a block helper <c>name</c> is invoked, or else <c>name</c> is resolved as a value:
/// <c>{{#if a}}A{{else b}}B{{/if}}</c> renders <c>B</c> only when <c>a</c> is falsy and <c>b</c> is truthy, and iterates when
/// <c>b</c> is a list. A bare <c>{{else if}}</c> / <c>{{else unless}}</c> with no condition is a <see cref="HandlebarsCompilerException"/>.</para>
/// <para>When <see langword="true"/>, the name is ignored and the branch renders as a plain <c>{{else}}</c>:
/// the template above renders <c>B</c> whenever <c>a</c> is falsy.</para>
/// <para>Read at compile time. Intended only as a temporary escape hatch for templates that depend on the old behavior.</para>
/// </summary>
public bool LegacyBareElseNameBehavior { get; set; } = false;
}
}
Loading