From d2613d6823f05e7c98a2439a1b8b5a9161fd142e Mon Sep 17 00:00:00 2001 From: "stencil-harness[bot]" <353851134+stencil-harness[bot]@users.noreply.github.com> Date: Sat, 21 Nov 2026 15:34:53 -0500 Subject: [PATCH 1/2] feat: scope inline partials to their block by default, with LegacyInlinePartialScoping opt-out Brings in the block-scoped inline partial implementation from #688 (which added it as the opt-in Compatibility.BlockScopedInlinePartials) and inverts it: handlebars.js scoping is now the default, and the earlier behavior is restored with Compatibility.LegacyInlinePartialScoping = true. The "Referenced partial name '...' could not be resolved" exception now names the opt-out when it is not set. Refs #673, #690 Co-Authored-By: Claude Opus 5.5 --- README.md | 23 +++ source/Handlebars.Test/InlinePartialTests.cs | 173 ++++++++++++++++++ source/Handlebars/Collections/CascadeIndex.cs | 16 ++ .../Expression/DecoratorDefinition.cs | 35 +++- .../Translation/Expression/PartialBinder.cs | 9 +- .../Handlebars/Configuration/Compatibility.cs | 14 ++ 6 files changed, 268 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index bbf4bb99..3f0213a5 100644 --- a/README.md +++ b/README.md @@ -467,6 +467,29 @@ public void LegacyStandaloneCaret() } ``` +#### `LegacyInlinePartialScoping` +By default 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 `true`, 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}}`). +Use 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 LegacyInlinePartialScoping() +{ + var handlebars = Handlebars.Create(); + handlebars.Configuration.Compatibility.LegacyInlinePartialScoping = true; + + var template = handlebars.Compile( + "{{#*inline \"p\"}}outer{{/inline}}{{#with .}}{{#*inline \"p\"}}inner{{/inline}}{{> p}}{{/with}} {{> p}}"); + + Assert.Equal("inner inner", template(new { })); // "inner outer" 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/InlinePartialTests.cs b/source/Handlebars.Test/InlinePartialTests.cs index 51c415a6..ba194587 100644 --- a/source/Handlebars.Test/InlinePartialTests.cs +++ b/source/Handlebars.Test/InlinePartialTests.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using HandlebarsDotNet.Compiler; using Xunit; namespace HandlebarsDotNet.Test @@ -484,6 +485,178 @@ public void BlockInlinePartialWithInlinePartials() var result4 = template(data); Assert.Equal("Hello Pete", result4); } + + // Inline partial scoping (handlebars.js semantics by default; Compatibility.LegacyInlinePartialScoping 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.LegacyInlinePartialScoping = true; + return handlebars; + } + + [Fact] + public void InlinePartialInBlockStaysRegisteredAfterBlockWithLegacyScoping() + { + var handlebars = CreateWithLegacyInlinePartialScoping(); + var template = handlebars.Compile( + "{{#*inline \"myPartial\"}}outer{{/inline}}" + + "{{#with .}}{{#*inline \"myPartial\"}}inner{{/inline}}{{> myPartial}}{{/with}} " + + "{{> myPartial}}"); + + Assert.Equal("inner inner", template(new { })); + + var after = handlebars.Compile("{{#with .}}{{#*inline \"myPartial\"}}success{{/inline}}{{/with}}{{> myPartial}}"); + Assert.Equal("success", after(new { })); + } + + [Fact] + public void InlinePartialsDeclaredInIncludedPartialRemainAvailableWithLegacyScoping() + { + var handlebars = CreateWithLegacyInlinePartialScoping(); + handlebars.RegisterTemplate("macros", "{{#*inline \"button\"}}{{/inline}}"); + + var template = handlebars.Compile("{{> macros}}{{> button label=\"OK\"}}"); + + Assert.Equal("", template(new { })); + } + + [Fact] + public void InlinePartialsDeclaredInIncludedPartialAreScopedToThatPartial() + { + var handlebars = Handlebars.Create(); + handlebars.RegisterTemplate("macros", "{{#*inline \"button\"}}{{/inline}}"); + + var template = handlebars.Compile("{{> macros}}{{> button label=\"OK\"}}"); + + var exception = Assert.Throws(() => template(new { })); + Assert.Contains("'button' could not be resolved", exception.Message); + } + + [Fact] + public void UnresolvedPartialMessageNamesLegacyInlinePartialScopingOptOut() + { + var handlebars = Handlebars.Create(); + var template = handlebars.Compile("{{#with .}}{{#*inline \"myPartial\"}}success{{/inline}}{{/with}}{{> myPartial}}"); + + var exception = Assert.Throws(() => template(new { })); + Assert.Contains("{{#*inline}} inside a block or another partial", exception.Message); + Assert.Contains("Configuration.Compatibility.LegacyInlinePartialScoping = true", exception.Message); + } + + [Fact] + public void UnresolvedPartialMessageOmitsOptOutWithLegacyScoping() + { + var handlebars = CreateWithLegacyInlinePartialScoping(); + var template = handlebars.Compile("{{> missing}}"); + + var exception = Assert.Throws(() => template(new { })); + Assert.Contains("'missing' could not be resolved", exception.Message); + Assert.DoesNotContain("LegacyInlinePartialScoping", exception.Message); + } + + // handlebars.js spec/partials.js: "should define inline partials for block" + [Fact] + public void InlinePartialIsScopedToDeclaringBlock() + { + var handlebars = Handlebars.Create(); + + var inside = handlebars.Compile("{{#with .}}{{#*inline \"myPartial\"}}success{{/inline}}{{> myPartial}}{{/with}}"); + Assert.Equal("success", inside(new { })); + + var outside = handlebars.Compile("{{#with .}}{{#*inline \"myPartial\"}}success{{/inline}}{{/with}}{{> myPartial}}"); + var exception = Assert.Throws(() => outside(new { })); + Assert.Contains("'myPartial' could not be resolved", exception.Message); + } + + [Fact] + public void InlinePartialInBlockOverridesOuterOnlyInsideBlock() + { + var handlebars = Handlebars.Create(); + var template = handlebars.Compile( + "{{#*inline \"myPartial\"}}outer{{/inline}}" + + "{{#with .}}{{#*inline \"myPartial\"}}inner{{/inline}}{{> myPartial}}{{/with}} " + + "{{> myPartial}}"); + + Assert.Equal("inner outer", template(new { })); + } + + [Fact] + public void InlinePartialInBlockIsVisibleToNestedBlocks() + { + var handlebars = Handlebars.Create(); + var template = handlebars.Compile( + "{{#with .}}{{#*inline \"myPartial\"}}success{{/inline}}" + + "{{#with .}}{{#if true}}{{> myPartial}}{{/if}}{{/with}}{{/with}}"); + + Assert.Equal("success", template(new { })); + } + + [Fact] + public void InlinePartialInEachIsScopedToLoop() + { + var handlebars = Handlebars.Create(); + var template = handlebars.Compile( + "{{#*inline \"item\"}}outer{{/inline}}" + + "{{#each items}}{{#*inline \"item\"}}[{{.}}]{{/inline}}{{> item}}{{/each}} {{> item}}"); + + Assert.Equal("[1][2] outer", template(new { items = new[] { 1, 2 } })); + } + + [Fact] + public void LastInlinePartialDefinitionInBlockWins() + { + var handlebars = Handlebars.Create(); + var template = handlebars.Compile( + "{{#with .}}{{#*inline \"p\"}}first{{/inline}}{{#*inline \"p\"}}second{{/inline}}{{> p}}{{/with}}"); + + Assert.Equal("second", template(new { })); + } + + [Fact] + public void InlinePartialsInBlockWithCustomDecoratorAreScopedToBlock() + { + var handlebars = Handlebars.Create(); + handlebars.RegisterDecorator("noop", + (TemplateDelegate function, in DecoratorOptions options, in Context context, in Arguments arguments) => function); + + var template = handlebars.Compile( + "{{#with .}}{{#*inline \"a\"}}A{{/inline}}{{*noop}}{{#*inline \"b\"}}B{{/inline}}{{> a}}{{> b}}{{/with}}{{> a}}"); + + var exception = Assert.Throws(() => template(new { })); + Assert.Contains("'a' could not be resolved", exception.Message); + + var inside = handlebars.Compile( + "{{#with .}}{{#*inline \"a\"}}A{{/inline}}{{*noop}}{{#*inline \"b\"}}B{{/inline}}{{> a}}{{> b}}{{/with}}"); + Assert.Equal("AB", inside(new { })); + } + + [Fact] + public void InlinePartialInPartialBlockIsScopedToPartialBlock() + { + var handlebars = Handlebars.Create(); + handlebars.RegisterTemplate("layout", "<{{> content}}>"); + + var template = handlebars.Compile( + "{{#> layout}}{{#*inline \"content\"}}inside{{/inline}}{{/layout}}"); + Assert.Equal("", template(new { })); + + var after = handlebars.Compile( + "{{#> layout}}{{#*inline \"content\"}}inside{{/inline}}{{/layout}}{{> content}}"); + var exception = Assert.Throws(() => after(new { })); + Assert.Contains("'content' could not be resolved", exception.Message); + } + + [Fact] + public void InlinePartialScopeIsRestoredOnRepeatedRenders() + { + var handlebars = Handlebars.Create(); + var template = handlebars.Compile( + "{{#*inline \"p\"}}outer{{/inline}}{{#with .}}{{#*inline \"p\"}}inner{{/inline}}{{> p}}{{/with}}{{> p}}"); + + Assert.Equal("innerouter", template(new { })); + Assert.Equal("innerouter", template(new { })); + } } } diff --git a/source/Handlebars/Collections/CascadeIndex.cs b/source/Handlebars/Collections/CascadeIndex.cs index 76227c6f..f0844756 100644 --- a/source/Handlebars/Collections/CascadeIndex.cs +++ b/source/Handlebars/Collections/CascadeIndex.cs @@ -48,6 +48,22 @@ public void Clear() _inner?.Clear(); } + /// + /// Makes subsequent calls write to a copy of the current own entries. + /// Pass the returned snapshot to to discard everything added since. + /// + internal DictionarySlim? BeginScope() + { + var snapshot = _inner; + if (snapshot != null) _inner = new DictionarySlim(snapshot); + return snapshot; + } + + internal void EndScope(DictionarySlim? snapshot) + { + _inner = snapshot; + } + public bool ContainsKey(in TKey key) { return (_inner?.ContainsKey(key) ?? false) diff --git a/source/Handlebars/Compiler/Translation/Expression/DecoratorDefinition.cs b/source/Handlebars/Compiler/Translation/Expression/DecoratorDefinition.cs index 50343553..95e69e8e 100644 --- a/source/Handlebars/Compiler/Translation/Expression/DecoratorDefinition.cs +++ b/source/Handlebars/Compiler/Translation/Expression/DecoratorDefinition.cs @@ -51,7 +51,40 @@ CompilationContext context f(writer, bindingContext, current(writer, bindingContext, function)); } - return decorator; + if (context.Configuration.Compatibility.LegacyInlinePartialScoping) return decorator; + + // Inline partials ({{#*inline}}) declared by a block's decorators are only visible + // while that block renders (handlebars.js semantics): open a partials scope on the + // frame before the decorators run and restore the previous set once the decorated + // function has executed. + var chain = decorator; + return (EncodedTextWriter writer, BindingContext bindingContext, TemplateDelegate function) => + { + var partials = bindingContext.InlinePartialTemplates; + var snapshot = partials.BeginScope(); + TemplateDelegate decorated; + try + { + decorated = chain(writer, bindingContext, function); + } + catch + { + partials.EndScope(snapshot); + throw; + } + + return (EncodedTextWriter w, BindingContext c) => + { + try + { + decorated(w, c); + } + finally + { + partials.EndScope(snapshot); + } + }; + }; } } } \ No newline at end of file diff --git a/source/Handlebars/Compiler/Translation/Expression/PartialBinder.cs b/source/Handlebars/Compiler/Translation/Expression/PartialBinder.cs index 6e20973f..9289cb55 100644 --- a/source/Handlebars/Compiler/Translation/Expression/PartialBinder.cs +++ b/source/Handlebars/Compiler/Translation/Expression/PartialBinder.cs @@ -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.LegacyInlinePartialScoping) + { + 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.LegacyInlinePartialScoping)} = true to restore the previous behavior."; + } + throw new HandlebarsRuntimeException(message); + } configuration.MissingPartialTemplateHandler.Handle(configuration, partialName, writer); return; diff --git a/source/Handlebars/Configuration/Compatibility.cs b/source/Handlebars/Configuration/Compatibility.cs index 0b67ab6b..b2c5bf64 100644 --- a/source/Handlebars/Configuration/Compatibility.cs +++ b/source/Handlebars/Configuration/Compatibility.cs @@ -31,5 +31,19 @@ public class Compatibility /// Intended only as a temporary escape hatch for templates that depend on the old behavior. /// public bool LegacyStandaloneCaretBehavior { get; set; } = false; + + /// + /// If restores the earlier Handlebars.Net scoping of inline partials ({{#*inline}}). + /// By default () an inline partial 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. Once the block has rendered it can no longer be called, and an outer partial with the same name + /// becomes visible again: {{#*inline "p"}}outer{{/inline}}{{#with .}}{{#*inline "p"}}inner{{/inline}}{{> p}}{{/with}} {{> p}} + /// renders inner outer. + /// When , such partials stay registered on the enclosing scope after the block ends, so the + /// template above renders inner inner, and a partial can declare inline partials for its caller to use + /// ({{> macros}}{{> button}}). + /// Intended only as a temporary escape hatch for templates that depend on the old behavior. + /// + public bool LegacyInlinePartialScoping { get; set; } = false; } } \ No newline at end of file From d1d40e4ae68e81d8d29970b629daa22ac8c34ce3 Mon Sep 17 00:00:00 2001 From: "stencil-harness[bot]" <353851134+stencil-harness[bot]@users.noreply.github.com> Date: Sat, 21 Nov 2026 15:34:59 -0500 Subject: [PATCH 2/2] feat: name LegacyStandaloneCaretBehavior in the repeated-else error when {{^}} caused it With {{^}} treated as the inverse separator, {{#if x}}a{{^}}b{{^}}c{{/if}} now fails with "'{{else}}' cannot follow another '{{else}}'". When the offending separator was a bare {{^}}, the message now explains that and names Compatibility.LegacyStandaloneCaretBehavior as the opt-out. Refs #690 Co-Authored-By: Claude Opus 5.5 --- .../HandlebarsSpecCoverageTests.cs | 24 +++++++++++++++++++ .../ConditionalBlockAccumulatorContext.cs | 9 ++++--- .../Converter/HelperArgumentAccumulator.cs | 4 ++-- .../Converter/InverseSeparatorConverter.cs | 2 +- .../Compiler/Structure/HelperExpression.cs | 6 +++++ 5 files changed, 39 insertions(+), 6 deletions(-) diff --git a/source/Handlebars.Test/HandlebarsSpecCoverageTests.cs b/source/Handlebars.Test/HandlebarsSpecCoverageTests.cs index d8e59c86..1a472846 100644 --- a/source/Handlebars.Test/HandlebarsSpecCoverageTests.cs +++ b/source/Handlebars.Test/HandlebarsSpecCoverageTests.cs @@ -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(() => 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( + () => 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() { diff --git a/source/Handlebars/Compiler/Lexer/Converter/BlockAccumulators/ConditionalBlockAccumulatorContext.cs b/source/Handlebars/Compiler/Lexer/Converter/BlockAccumulators/ConditionalBlockAccumulatorContext.cs index cbd87559..316592b8 100644 --- a/source/Handlebars/Compiler/Lexer/Converter/BlockAccumulators/ConditionalBlockAccumulatorContext.cs +++ b/source/Handlebars/Compiler/Lexer/Converter/BlockAccumulators/ConditionalBlockAccumulatorContext.cs @@ -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))); diff --git a/source/Handlebars/Compiler/Lexer/Converter/HelperArgumentAccumulator.cs b/source/Handlebars/Compiler/Lexer/Converter/HelperArgumentAccumulator.cs index 10bed2bf..604c985e 100644 --- a/source/Handlebars/Compiler/Lexer/Converter/HelperArgumentAccumulator.cs +++ b/source/Handlebars/Compiler/Lexer/Converter/HelperArgumentAccumulator.cs @@ -29,12 +29,12 @@ public override IEnumerable ConvertTokens(IEnumerable 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; } diff --git a/source/Handlebars/Compiler/Lexer/Converter/InverseSeparatorConverter.cs b/source/Handlebars/Compiler/Lexer/Converter/InverseSeparatorConverter.cs index 6cf9f83b..4e0a6e4c 100644 --- a/source/Handlebars/Compiler/Lexer/Converter/InverseSeparatorConverter.cs +++ b/source/Handlebars/Compiler/Lexer/Converter/InverseSeparatorConverter.cs @@ -38,7 +38,7 @@ public override IEnumerable ConvertTokens(IEnumerable 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++; } } diff --git a/source/Handlebars/Compiler/Structure/HelperExpression.cs b/source/Handlebars/Compiler/Structure/HelperExpression.cs index be0f4f69..3a32a77a 100644 --- a/source/Handlebars/Compiler/Structure/HelperExpression.cs +++ b/source/Handlebars/Compiler/Structure/HelperExpression.cs @@ -34,6 +34,12 @@ public HelperExpression(string helperName, bool isBlock, bool isRaw = false, IRe public bool IsBlock { get; set; } + /// + /// for an else marker produced from a bare {{^}} by , + /// so errors about it can point at . + /// + public bool IsStandaloneCaret { get; set; } + public IEnumerable Arguments { get; } public IReaderContext? Context { get; } }