Skip to content
Open
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
46 changes: 46 additions & 0 deletions source/Handlebars.Test/HandlebarsSpec.md
Original file line number Diff line number Diff line change
Expand Up @@ -1674,6 +1674,52 @@ behavior is purely additive with zero breakage to existing working templates.

---

### Gap 5: A section over the number `0` is skipped

**Behavioral gap:**
Handlebars.js `blockHelperMissing` only treats `false`, `null`/`undefined` and empty arrays as "skip the block";
any other value (including `0` and `""`) renders the block once with that value as the context
(spec/regressions.js GH-731 "zero context rendering"):
```
Template: {{#foo}} This is {{bar}} ~ {{/foo}}
Data: { foo: 0, bar: "OK" }
Handlebars.js: " This is ~ "
Handlebars.Net: ""
```

**Technical root cause:**
A `{{#name}}` section over a plain (non-helper) value uses the same falsy test as `{{#if}}`, where `0` is falsy.

**Backward-compatibility risk: HIGH.**
Templates such as `{{#unreadCount}}You have {{.}} new messages{{/unreadCount}}` rely on `0` hiding the block today;
matching Handlebars.js would make them start rendering "You have 0 new messages". Changing this needs either a
major version or an opt-in compatibility flag.

**Regression test:** `Section_ZeroValueSkipsBlock_SpecGap` (asserts `""`).

---

### Gap 6: Explicitly calling `helperMissing` / `blockHelperMissing` renders empty instead of throwing

**Behavioral gap:**
Since 4.6 (GH-1558), Handlebars.js throws when a template calls `{{helperMissing}}` or
`{{#helperMissing}}{{/helperMissing}}` directly, unless the runtime option `allowExplicitCallOfHelperMissing` is set.
Handlebars.Net runs the built-in hooks and renders `""`.

**Technical root cause:**
`Features/MissingHelperFeature.cs` registers `helperMissing` and `blockHelperMissing` as ordinary named helpers,
so templates can reference them like any other helper. There is no `allowExplicitCallOfHelperMissing` option.

**Backward-compatibility risk: MEDIUM.**
The Handlebars.js restriction is a defence against untrusted templates calling the hooks directly; with the default
hooks, a direct call in Handlebars.Net only renders nothing. Throwing would break any template that renders today
with such a call (for example one that invokes a custom `helperMissing` hook registered via `RegisterMissingHelperHook`
or `RegisterHelper("helperMissing", ...)`). Matching Handlebars.js needs an opt-in option or a major version.

**Regression test:** `HelperMissing_ExplicitCallRendersEmpty_SpecGap` (asserts `""`).

---

## Coverage Gaps (Priority Areas for New Tests)

1. HTML encoding: `'`, `` ` ``, `=` characters specifically
Expand Down
94 changes: 94 additions & 0 deletions source/Handlebars.Test/HandlebarsSpecCoverageTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1268,5 +1268,99 @@
Assert.Equal("0", hbs.Compile("{{val}}")(new { val = 0 }));
Assert.Equal("no", hbs.Compile("{{#if val}}yes{{else}}no{{/if}}")(new { val = 0 }));
}

// ─────────────────────────────────────────────────────────────
// 23. LITERAL NAMES: QUOTED-STRING PATHS, NUMERIC PARTIAL NAMES, {{#.}} SECTIONS
// https://github.com/Handlebars-Net/Handlebars.Net/issues/702
// ─────────────────────────────────────────────────────────────

// handlebars.js spec/security.js "escapes template variables"
[Theory, ClassData(typeof(HandlebarsEnvGenerator))]
public void LiteralPath_QuotedStringWithBackslashIsLookedUpAsKey(IHandlebars hbs)
{
var data = new Dictionary<string, object> { ["a\\b"] = "c" };
Assert.Equal("c", hbs.Compile("{{'a\\b'}}")(data));
Assert.Equal("c", hbs.Compile("{{\"a\\b\"}}")(data));
}

// handlebars.js spec/basic.js "literal references": {{"foo bar"}} is the same as {{[foo bar]}}
[Theory, ClassData(typeof(HandlebarsEnvGenerator))]
public void LiteralPath_QuotedStringIsLookedUpAsSingleSegment(IHandlebars hbs)
{
var data = new Dictionary<string, object>
{
["foo bar"] = "spaced",
["a.b"] = "dotted",
["a"] = new Dictionary<string, object> { ["b"] = "nested" },
};
Assert.Equal("spaced|spaced|dotted", hbs.Compile("{{'foo bar'}}|{{\"foo bar\"}}|{{'a.b'}}")(data));
Assert.Equal("", hbs.Compile("{{'missing'}}")(data));
Assert.Equal("&lt;b&gt;|<b>", hbs.Compile("{{'k'}}|{{{'k'}}}")(new Dictionary<string, object> { ["k"] = "<b>" }));
}

[Theory, ClassData(typeof(HandlebarsEnvGenerator))]
public void LiteralPath_QuotedStringResolvesHelperLikeSegmentLiteral(IHandlebars hbs)
{
hbs.RegisterHelper("shout", (writer, context, arguments) => writer.WriteSafeString("SHOUT"));
Assert.Equal(hbs.Compile("{{[shout]}}")(new { }), hbs.Compile("{{'shout'}}")(new { }));
}

[Theory, ClassData(typeof(HandlebarsEnvGenerator))]
public void LiteralPath_QuotedStringInsideRawBlockIsLeftVerbatim(IHandlebars hbs)
{
hbs.RegisterHelper("raw", (writer, options, context, arguments) => options.Template(writer, null!));
var template = hbs.Compile("{{{{raw}}}}{{'x'}} {{\"y z\"}}{{{{/raw}}}}");
Assert.Equal("{{'x'}} {{\"y z\"}}", template(new { x = "X" }));
}

// handlebars.js spec/partials.js "partials with literal paths" / numeric partial name
[Theory, ClassData(typeof(HandlebarsEnvGenerator))]
public void Partial_NumericNameResolvesRegisteredTemplate(IHandlebars hbs)
{
hbs.RegisterTemplate("404", "{{name}}");
var data = new Dictionary<string, object> { ["name"] = "Jeepers" };
Assert.Equal("Dudes: Jeepers", hbs.Compile("Dudes: {{> 404}}")(data));
Assert.Equal("Dudes: Jeepers", hbs.Compile("Dudes: {{> '404'}}")(data));
}

// handlebars.js spec/regressions.js GH-408 "multiple loops fail"
[Theory, ClassData(typeof(HandlebarsEnvGenerator))]
public void Section_DotIteratesCurrentContextLikeThis(IHandlebars hbs)
{
var people = new object[]
{
new Dictionary<string, object> { ["name"] = "John Doe" },
new Dictionary<string, object> { ["name"] = "Jane Doe" },
};
var template = hbs.Compile("{{#.}}{{name}}{{/.}}{{#.}}{{name}}{{/.}}{{#.}}{{name}}{{/.}}");
Assert.Equal("John DoeJane DoeJohn DoeJane DoeJohn DoeJane Doe", template(people));
Assert.Equal(hbs.Compile("{{#this}}{{name}}{{/this}}")(people), hbs.Compile("{{#.}}{{name}}{{/.}}")(people));
Assert.Equal("empty", hbs.Compile("{{^.}}empty{{/.}}")(new object[0]));

Check warning on line 1338 in source/Handlebars.Test/HandlebarsSpecCoverageTests.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

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

See more on https://sonarcloud.io/project/issues?id=Handlebars-Net_Handlebars.Net&issues=AaIStUNsKHR5OEKWeS_E&open=AaIStUNsKHR5OEKWeS_E&pullRequest=703
}

// [SPEC GAP] handlebars.js spec/regressions.js GH-731 "zero context rendering"
// SPEC: {{#foo}} with foo = 0 renders the block once with 0 as context → " This is ~ "
// CURRENT: 0 is treated as falsy for a section, so the block is skipped → ""
// SOURCE: block sections over a non-helper value use the same falsy test as #if
// COMPAT: HIGH — templates such as {{#count}}…{{/count}} with count = 0 would start rendering
[Theory, ClassData(typeof(HandlebarsEnvGenerator))]
public void Section_ZeroValueSkipsBlock_SpecGap(IHandlebars hbs)
{
var data = new Dictionary<string, object> { ["foo"] = 0, ["bar"] = "OK" };
Assert.Equal("", hbs.Compile("{{#foo}} This is {{bar}} ~ {{/foo}}")(data));
}

// [SPEC GAP] handlebars.js spec/security.js GH-1558 "should not allow explicit call of helperMissing"
// SPEC: {{helperMissing}} and {{#helperMissing}}{{/helperMissing}} throw unless allowExplicitCallOfHelperMissing
// CURRENT: the built-in helperMissing / blockHelperMissing run and render nothing
// SOURCE: Features/MissingHelperFeature.cs registers them as ordinary named helpers
// COMPAT: MEDIUM — templates that call the hook directly and render today would throw
[Theory, ClassData(typeof(HandlebarsEnvGenerator))]
public void HelperMissing_ExplicitCallRendersEmpty_SpecGap(IHandlebars hbs)
{
var data = new Dictionary<string, object>();
Assert.Equal("", hbs.Compile("{{helperMissing}}")(data));
Assert.Equal("", hbs.Compile("{{#helperMissing}}{{/helperMissing}}")(data));
}
}
}
1 change: 1 addition & 0 deletions source/Handlebars/Compiler/ExpressionBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ public static IEnumerable<Expression> ConvertTokensToExpressions(IEnumerable<obj
{
tokens = HelperConverter.Convert(tokens, configuration);
tokens = RawHelperAccumulator.Accumulate(tokens);
tokens = LoneStringLiteralConverter.Convert(tokens, configuration);
tokens = InverseSeparatorConverter.Convert(tokens, configuration);
tokens = CommentAndLayoutConverter.Convert(tokens);
tokens = LiteralConverter.Convert(tokens);
Expand Down
22 changes: 16 additions & 6 deletions source/Handlebars/Compiler/Lexer/Converter/HelperConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -70,16 +70,18 @@ public override IEnumerable<object> ConvertTokens(IEnumerable<object> sequence)
}
}

private bool IsRegisteredHelperName(string name)
private bool IsRegisteredHelperName(string name) => IsRegisteredHelperName(name, _configuration);

internal static bool IsRegisteredHelperName(string name, ICompiledHandlebarsConfiguration configuration)
{
var pathInfo = PathInfo.Parse(name);
#pragma warning disable CS0618
if (!pathInfo.IsValidHelperLiteral && !_configuration.Compatibility.RelaxedHelperNaming) return false;
if (!pathInfo.IsValidHelperLiteral && !configuration.Compatibility.RelaxedHelperNaming) return false;
#pragma warning restore CS0618
if (pathInfo.IsBlockHelper || pathInfo.IsInversion || pathInfo.IsBlockClose || pathInfo.IsThis) return false;
name = pathInfo.TrimmedPath!;
return _configuration.Helpers.ContainsKey(pathInfo) || _configuration.Decorators.ContainsKey(pathInfo) || BuiltInHelpers.Contains(name);

return configuration.Helpers.ContainsKey(pathInfo) || configuration.Decorators.ContainsKey(pathInfo) || BuiltInHelpers.Contains(name);
}

private bool IsRegisteredBlockHelperName(string name, bool isRaw)
Expand All @@ -101,9 +103,9 @@ private bool IsUnregisteredBlockHelperName(string name, bool isRaw, IEnumerable<
{
var pathInfo = PathInfo.Parse(name);
#pragma warning disable CS0618
if (!pathInfo.IsValidHelperLiteral && !_configuration.Compatibility.RelaxedHelperNaming) return false;
if (!pathInfo.IsValidHelperLiteral && !_configuration.Compatibility.RelaxedHelperNaming && !IsCurrentContextBlock(name)) return false;
#pragma warning restore CS0618

if (!isRaw && !(pathInfo.IsBlockHelper || pathInfo.IsInversion)) return false;
if (pathInfo.IsBlockClose) return false;
name = name.Substring(1);
Expand All @@ -117,6 +119,14 @@ private bool IsUnregisteredBlockHelperName(string name, bool isRaw, IEnumerable<
string.Equals(o.Value, expectedBlockName, StringComparison.OrdinalIgnoreCase));
}

/// <summary>
/// "{{#.}}" / "{{^.}}" open a section over the current context, the same as "{{#this}}" / "{{^this}}".
/// </summary>
private static bool IsCurrentContextBlock(string name)
{
return name.Length == 2 && (name[0] == '#' || name[0] == '^') && name[1] == '.';
}

private static object GetNext(IEnumerator<object> enumerator)
{
enumerator.MoveNext();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
using System.Collections.Generic;
using System.Linq;
using HandlebarsDotNet.Compiler.Lexer;

namespace HandlebarsDotNet.Compiler
{
/// <summary>
/// Handlebars.js resolves a mustache consisting of a single quoted string, e.g. <c>{{'foo bar'}}</c>,
/// as a path made of that one literal segment, i.e. the same as <c>{{[foo bar]}}</c>.
/// This rewrites such literals into exactly what <see cref="HelperConverter"/> produces for the equivalent
/// segment literal, so they go through normal helper / path resolution.
/// Literals that cannot be expressed as a segment literal (empty, or containing <c>]</c>) are left untouched.
/// </summary>
/// <remarks>
/// Must run after <see cref="RawHelperAccumulator"/>, which rebuilds raw-block content from the original tokens.
/// </remarks>
internal static class LoneStringLiteralConverter
{
public static IEnumerable<object> Convert(IEnumerable<object> sequence, ICompiledHandlebarsConfiguration configuration)
{
var tokens = sequence.ToList();
for (var index = 1; index < tokens.Count - 1; index++)
{
if (tokens[index] is LiteralExpressionToken { IsDelimitedLiteral: true } literal
&& tokens[index - 1] is StartExpressionToken start
&& tokens[index + 1] is EndExpressionToken
&& literal.Value.Length > 0
&& literal.Value.IndexOf(']') < 0)
{
var name = $"[{literal.Value}]";
tokens[index] = HelperConverter.IsRegisteredHelperName(name, configuration)
? HandlebarsExpression.Helper(name, false, start.IsRaw, literal.Context)
: Token.Word(name, literal.Context);
}
}

return tokens;
}
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using HandlebarsDotNet.Compiler.Lexer;
Expand Down Expand Up @@ -39,6 +40,12 @@ public override IEnumerable<object> ConvertTokens(IEnumerable<object> sequence)
{
partialName = Expression.Constant(expression.Path);
}
else if (partialName is UnaryExpression { NodeType: ExpressionType.Convert, Operand: ConstantExpression { Value: not string and not null } constant })
{
// Undelimited literals such as "{{> 404}}" or "{{> true}}" were typed as numbers/booleans
// by LiteralConverter; as a partial name they mean the template registered under that text.
partialName = Expression.Constant(System.Convert.ToString(constant.Value, CultureInfo.InvariantCulture));
}

switch (arguments.Count)
{
Expand Down
Loading