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
13 changes: 6 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -468,26 +468,25 @@ public void LegacyStandaloneCaret()
```

#### `BlockScopedInlinePartials`
If `true`, an inline partial (`{{#*inline}}`) declared inside a block (`{{#with}}`, `{{#each}}`, `{{#> layout}}`, a custom block helper) or inside an included partial is visible only in that block and its children, as in Handlebarsjs. After the block it can no longer be called, and an outer partial with the same name is visible again.
By default (`false`) the earlier Handlebars.Net behavior is kept: such partials stay registered for the rest of the enclosing template.

Before enabling, move any inline partial you call after its block to the top level of the template, or register it with `RegisterTemplate`. Otherwise those calls throw `Referenced partial name '…' could not be resolved`, or produce `MissingPartialTemplateHandler` output if a handler is configured.
By default (`true`) an inline partial (`{{#*inline}}`) declared inside a block (`{{#with}}`, `{{#each}}`, `{{#> layout}}`, a custom block helper) or inside an included partial is visible only in that block and its children, as in Handlebarsjs. After the block it can no longer be called, and an outer partial with the same name is visible again. Calling it after the block throws `Referenced partial name '…' could not be resolved` (or produces `MissingPartialTemplateHandler` output if a handler is configured).
If `false`, restores the earlier Handlebars.Net behavior where such partials stay registered for the rest of the enclosing template, including partials declared inside an included partial (`{{> macros}}{{> button}}`). This was the default up to 2.4.x.
Use `false` only as a temporary escape hatch; the long-term fix is to declare shared inline partials at the top level of the template, or register them with `RegisterTemplate`.

##### Areas
- `Compile-time`

##### Example
```c#
[Fact]
public void BlockScopedInlinePartials()
public void LegacyInlinePartialScoping()
{
var handlebars = Handlebars.Create();
handlebars.Configuration.Compatibility.BlockScopedInlinePartials = true;
handlebars.Configuration.Compatibility.BlockScopedInlinePartials = false;

var template = handlebars.Compile(
"{{#*inline \"p\"}}outer{{/inline}}{{#with .}}{{#*inline \"p\"}}inner{{/inline}}{{> p}}{{/with}} {{> p}}");

Assert.Equal("inner outer", template(new { })); // "inner inner" with the default behavior
Assert.Equal("inner inner", template(new { })); // "inner outer" with the default behavior
}
```

Expand Down
24 changes: 24 additions & 0 deletions source/Handlebars.Test/HandlebarsSpecCoverageTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1024,6 +1024,30 @@ public void InvertedSection_InlineCaretSyntaxIsDefaultBehavior()
Assert.False(new HandlebarsConfiguration().Compatibility.LegacyStandaloneCaretBehavior);
}

// https://github.com/Handlebars-Net/Handlebars.Net/issues/690
[Theory]
[InlineData("{{#if x}}a{{^}}b{{^}}c{{/if}}")]
[InlineData("{{#unless x}}a{{else}}b{{^}}c{{/unless}}")]
public void InvertedSection_RepeatedInlineCaretErrorNamesLegacyOptOut(string source)
{
var exception = Assert.Throws<HandlebarsCompilerException>(() => Handlebars.Create().Compile(source));
Assert.Contains("cannot follow another '{{else}}'", exception.Message);
Assert.Contains("Configuration.Compatibility.LegacyStandaloneCaretBehavior = true", exception.Message);

var legacy = Handlebars.Create();
legacy.Configuration.Compatibility.LegacyStandaloneCaretBehavior = true;
legacy.Compile(source);
}

[Fact]
public void InvertedSection_RepeatedElseErrorOmitsCaretOptOut()
{
var exception = Assert.Throws<HandlebarsCompilerException>(
() => Handlebars.Create().Compile("{{#if x}}a{{^}}b{{else}}c{{/if}}"));
Assert.Contains("cannot follow another '{{else}}'", exception.Message);
Assert.DoesNotContain("LegacyStandaloneCaretBehavior", exception.Message);
}

[Fact]
public void InvertedSection_InlineCaretSyntaxIsLiteralInsideRawBlock()
{
Expand Down
71 changes: 56 additions & 15 deletions source/Handlebars.Test/InlinePartialTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -486,18 +486,25 @@ public void BlockInlinePartialWithInlinePartials()
Assert.Equal("Hello Pete", result4);
}

// Compatibility.BlockScopedInlinePartials (opt-in) — https://github.com/Handlebars-Net/Handlebars.Net/issues/673
private static IHandlebars CreateWithBlockScopedInlinePartials()
// Inline partial scoping (handlebars.js semantics by default; Compatibility.BlockScopedInlinePartials = false opts out)
// https://github.com/Handlebars-Net/Handlebars.Net/issues/673, https://github.com/Handlebars-Net/Handlebars.Net/issues/690
private static IHandlebars CreateWithLegacyInlinePartialScoping()
{
var handlebars = Handlebars.Create();
handlebars.Configuration.Compatibility.BlockScopedInlinePartials = true;
handlebars.Configuration.Compatibility.BlockScopedInlinePartials = false;
return handlebars;
}

[Fact]
public void InlinePartialInBlockStaysRegisteredAfterBlockByDefault()
public void BlockScopedInlinePartialsIsDefaultBehavior()
{
var handlebars = Handlebars.Create();
Assert.True(new HandlebarsConfiguration().Compatibility.BlockScopedInlinePartials);
}

[Fact]
public void InlinePartialInBlockStaysRegisteredAfterBlockWithLegacyScoping()
{
var handlebars = CreateWithLegacyInlinePartialScoping();
var template = handlebars.Compile(
"{{#*inline \"myPartial\"}}outer{{/inline}}" +
"{{#with .}}{{#*inline \"myPartial\"}}inner{{/inline}}{{> myPartial}}{{/with}} " +
Expand All @@ -510,21 +517,55 @@ public void InlinePartialInBlockStaysRegisteredAfterBlockByDefault()
}

[Fact]
public void InlinePartialsDeclaredInIncludedPartialRemainAvailableByDefault()
public void InlinePartialsDeclaredInIncludedPartialRemainAvailableWithLegacyScoping()
{
var handlebars = Handlebars.Create();
var handlebars = CreateWithLegacyInlinePartialScoping();
handlebars.RegisterTemplate("macros", "{{#*inline \"button\"}}<button>{{label}}</button>{{/inline}}");

var template = handlebars.Compile("{{> macros}}{{> button label=\"OK\"}}");

Assert.Equal("<button>OK</button>", template(new { }));
}

[Fact]
public void InlinePartialsDeclaredInIncludedPartialAreScopedToThatPartial()
{
var handlebars = Handlebars.Create();
handlebars.RegisterTemplate("macros", "{{#*inline \"button\"}}<button>{{label}}</button>{{/inline}}");

var template = handlebars.Compile("{{> macros}}{{> button label=\"OK\"}}");

var exception = Assert.Throws<HandlebarsRuntimeException>(() => template(new { }));
Assert.Contains("'button' could not be resolved", exception.Message);
}

[Fact]
public void UnresolvedPartialMessageNamesBlockScopedInlinePartialsOptOut()
{
var handlebars = Handlebars.Create();
var template = handlebars.Compile("{{#with .}}{{#*inline \"myPartial\"}}success{{/inline}}{{/with}}{{> myPartial}}");

var exception = Assert.Throws<HandlebarsRuntimeException>(() => template(new { }));
Assert.Contains("{{#*inline}} inside a block or another partial", exception.Message);
Assert.Contains("Configuration.Compatibility.BlockScopedInlinePartials = false", exception.Message);
}

[Fact]
public void UnresolvedPartialMessageOmitsOptOutWithLegacyScoping()
{
var handlebars = CreateWithLegacyInlinePartialScoping();
var template = handlebars.Compile("{{> missing}}");

var exception = Assert.Throws<HandlebarsRuntimeException>(() => template(new { }));
Assert.Contains("'missing' could not be resolved", exception.Message);
Assert.DoesNotContain("BlockScopedInlinePartials", exception.Message);
}

// handlebars.js spec/partials.js: "should define inline partials for block"
[Fact]
public void InlinePartialIsScopedToDeclaringBlock()
{
var handlebars = CreateWithBlockScopedInlinePartials();
var handlebars = Handlebars.Create();

var inside = handlebars.Compile("{{#with .}}{{#*inline \"myPartial\"}}success{{/inline}}{{> myPartial}}{{/with}}");
Assert.Equal("success", inside(new { }));
Expand All @@ -537,7 +578,7 @@ public void InlinePartialIsScopedToDeclaringBlock()
[Fact]
public void InlinePartialInBlockOverridesOuterOnlyInsideBlock()
{
var handlebars = CreateWithBlockScopedInlinePartials();
var handlebars = Handlebars.Create();
var template = handlebars.Compile(
"{{#*inline \"myPartial\"}}outer{{/inline}}" +
"{{#with .}}{{#*inline \"myPartial\"}}inner{{/inline}}{{> myPartial}}{{/with}} " +
Expand All @@ -549,7 +590,7 @@ public void InlinePartialInBlockOverridesOuterOnlyInsideBlock()
[Fact]
public void InlinePartialInBlockIsVisibleToNestedBlocks()
{
var handlebars = CreateWithBlockScopedInlinePartials();
var handlebars = Handlebars.Create();
var template = handlebars.Compile(
"{{#with .}}{{#*inline \"myPartial\"}}success{{/inline}}" +
"{{#with .}}{{#if true}}{{> myPartial}}{{/if}}{{/with}}{{/with}}");
Expand All @@ -560,7 +601,7 @@ public void InlinePartialInBlockIsVisibleToNestedBlocks()
[Fact]
public void InlinePartialInEachIsScopedToLoop()
{
var handlebars = CreateWithBlockScopedInlinePartials();
var handlebars = Handlebars.Create();
var template = handlebars.Compile(
"{{#*inline \"item\"}}outer{{/inline}}" +
"{{#each items}}{{#*inline \"item\"}}[{{.}}]{{/inline}}{{> item}}{{/each}} {{> item}}");
Expand All @@ -571,7 +612,7 @@ public void InlinePartialInEachIsScopedToLoop()
[Fact]
public void LastInlinePartialDefinitionInBlockWins()
{
var handlebars = CreateWithBlockScopedInlinePartials();
var handlebars = Handlebars.Create();
var template = handlebars.Compile(
"{{#with .}}{{#*inline \"p\"}}first{{/inline}}{{#*inline \"p\"}}second{{/inline}}{{> p}}{{/with}}");

Expand All @@ -581,7 +622,7 @@ public void LastInlinePartialDefinitionInBlockWins()
[Fact]
public void InlinePartialsInBlockWithCustomDecoratorAreScopedToBlock()
{
var handlebars = CreateWithBlockScopedInlinePartials();
var handlebars = Handlebars.Create();
handlebars.RegisterDecorator("noop",
(TemplateDelegate function, in DecoratorOptions options, in Context context, in Arguments arguments) => function);

Expand All @@ -599,7 +640,7 @@ public void InlinePartialsInBlockWithCustomDecoratorAreScopedToBlock()
[Fact]
public void InlinePartialInPartialBlockIsScopedToPartialBlock()
{
var handlebars = CreateWithBlockScopedInlinePartials();
var handlebars = Handlebars.Create();
handlebars.RegisterTemplate("layout", "<{{> content}}>");

var template = handlebars.Compile(
Expand All @@ -615,7 +656,7 @@ public void InlinePartialInPartialBlockIsScopedToPartialBlock()
[Fact]
public void InlinePartialScopeIsRestoredOnRepeatedRenders()
{
var handlebars = CreateWithBlockScopedInlinePartials();
var handlebars = Handlebars.Create();
var template = handlebars.Compile(
"{{#*inline \"p\"}}outer{{/inline}}{{#with .}}{{#*inline \"p\"}}inner{{/inline}}{{> p}}{{/with}}{{> p}}");

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,12 @@ public override void HandleElement(Expression item)
{
if (_currentCondition == null)
{
throw new HandlebarsCompilerException(
$"'{{{{else}}}}' cannot follow another '{{{{else}}}}' in the same '{BlockName}' block",
GetReaderContext(item));
var message = $"'{{{{else}}}}' cannot follow another '{{{{else}}}}' in the same '{BlockName}' block";
if (UnwrapStatement(item) is HelperExpression { IsStandaloneCaret: true })
{
message += $". A bare '{{{{^}}}}' is the inverse separator, equivalent to '{{{{else}}}}'; to restore the previous behavior, where it rendered the current context, set Configuration.Compatibility.{nameof(Compatibility.LegacyStandaloneCaretBehavior)} = true";
}
throw new HandlebarsCompilerException(message, GetReaderContext(item));
}

_conditionalBlock.Add(Expression.IfThen(_currentCondition, SinglifyExpressions(_bodyBuffer)));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,12 @@ public override IEnumerable<object> ConvertTokens(IEnumerable<object> sequence)
case HelperExpression helper:
{
var helperArguments = AccumulateArguments(enumerator);
yield return HandlebarsExpression.Helper(
yield return new HelperExpression(
helper.HelperName,
helper.IsBlock,
helperArguments,
helper.IsRaw,
helper.Context);
helper.Context) { IsStandaloneCaret = helper.IsStandaloneCaret };
yield return enumerator.Current!;
break;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public override IEnumerable<object> ConvertTokens(IEnumerable<object> sequence)
&& word.Value == "^"
&& items[index + 2] is EndExpressionToken)
{
yield return HandlebarsExpression.Helper("else", false, false, word.Context);
yield return new HelperExpression("else", false, false, word.Context) { IsStandaloneCaret = true };
index++;
}
}
Expand Down
6 changes: 6 additions & 0 deletions source/Handlebars/Compiler/Structure/HelperExpression.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,12 @@ public HelperExpression(string helperName, bool isBlock, bool isRaw = false, IRe

public bool IsBlock { get; set; }

/// <summary>
/// <see langword="true"/> for an <c>else</c> marker produced from a bare <c>{{^}}</c> by <see cref="InverseSeparatorConverter"/>,
/// so errors about it can point at <see cref="Compatibility.LegacyStandaloneCaretBehavior"/>.
/// </summary>
public bool IsStandaloneCaret { get; set; }

public IEnumerable<Expression> Arguments { get; }
public IReaderContext? Context { get; }
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,14 @@ private static void InvokePartialWithFallback(
if (context.PartialBlockTemplate == null)
{
if (configuration.MissingPartialTemplateHandler == null)
throw new HandlebarsRuntimeException($"Referenced partial name '{partialName}' could not be resolved. If you registered the partial on the static Handlebars class, make sure to also compile and render using the same static class (or register the partial on the IHandlebars instance you are using to compile).");
{
var message = $"Referenced partial name '{partialName}' could not be resolved. If you registered the partial on the static Handlebars class, make sure to also compile and render using the same static class (or register the partial on the IHandlebars instance you are using to compile).";
if (configuration.Compatibility.BlockScopedInlinePartials)
{
message += $" If '{partialName}' is declared with {{{{#*inline}}}} inside a block or another partial, it is only visible within that block; move the declaration to the top level of the template, or set Configuration.Compatibility.{nameof(Compatibility.BlockScopedInlinePartials)} = false to restore the previous behavior.";
}
throw new HandlebarsRuntimeException(message);
}

configuration.MissingPartialTemplateHandler.Handle(configuration, partialName, writer);
return;
Expand Down
22 changes: 12 additions & 10 deletions source/Handlebars/Configuration/Compatibility.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public class Compatibility
/// </summary>
[Obsolete("@last is supported on Handlebarsjs, so it is always enabled, and the setting should be removed.")]
public bool SupportLastInObjectIterations { get; set; } = true;

/// <summary>
/// If <see langword="true"/> enables support for Handlebars.Net helper naming rules.
/// <para>This enables helper names to be not-valid Handlebars identifiers (e.g. <code>{{ one.two }}</code>)</para>
Expand All @@ -33,14 +33,16 @@ public class Compatibility
public bool LegacyStandaloneCaretBehavior { get; set; } = false;

/// <summary>
/// If <see langword="true"/> limits an inline partial (<c>{{#*inline}}</c>) declared inside a block to that block, as in Handlebarsjs.
/// <para>The partial is visible in the declaring block and its children only; once the block has rendered it can no longer be
/// called, and an outer partial with the same name becomes visible again:
/// <c>{{#*inline "p"}}outer{{/inline}}{{#with .}}{{#*inline "p"}}inner{{/inline}}{{> p}}{{/with}} {{> p}}</c> renders <c>inner outer</c>.</para>
/// <para>By default (<see langword="false"/>) the earlier Handlebars.Net behavior is kept: inline partials declared inside a block
/// (or inside a partial) stay registered on the enclosing scope after it ends, so the template above renders <c>inner inner</c>.</para>
/// <para>Templates that call a block's inline partial after the block will throw "could not be resolved" when this is enabled.</para>
/// If <see langword="true"/> (the default) limits an inline partial (<c>{{#*inline}}</c>) declared inside a block
/// (<c>{{#with}}</c>, <c>{{#each}}</c>, <c>{{#> layout}}</c>, a custom block helper) or inside an included partial
/// to that block and its children, as in Handlebarsjs. Once the block has rendered it can no longer be called, and an
/// outer partial with the same name becomes visible again:
/// <c>{{#*inline "p"}}outer{{/inline}}{{#with .}}{{#*inline "p"}}inner{{/inline}}{{> p}}{{/with}} {{> p}}</c> renders <c>inner outer</c>.
/// <para>Set to <see langword="false"/> to restore the earlier Handlebars.Net behavior: such partials stay registered on the
/// enclosing scope after the block ends, so the template above renders <c>inner inner</c>, and a partial can declare inline
/// partials for its caller to use (<c>{{> macros}}{{> button}}</c>).</para>
/// <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; } = false;
public bool BlockScopedInlinePartials { get; set; } = true;
}
}
}
Loading