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
36 changes: 36 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,42 @@ var result = template(data); // "6"

This is a C#-specific capability, since JavaScript/Handlebars.js has no equivalent to true multi-dimensional arrays.

### System.Text.Json

`System.Text.Json` values can be passed to a template directly, with no conversion to POCOs or dictionaries.

**`JsonElement`**: deserializing JSON as `object` with `JsonSerializer.Deserialize<object>(json)` gives you a `JsonElement`. You can pass that in, or any other `JsonElement` such as `JsonDocument.RootElement`.

**`JsonNode`**: `JsonObject`, `JsonArray` and `JsonValue` work too, whether they come from `JsonNode.Parse` or are built in code. A node tree is read when the template renders, so changes made to it between renders show up in the output.

```c#
var template = Handlebars.Compile("{{title}}: {{#each tags}}{{@index}}={{this}} {{/each}}{{#if draft}}(draft){{/if}}");

var json = @"{ ""title"": ""My post"", ""tags"": [""a"", ""b""], ""draft"": false }";

template(JsonSerializer.Deserialize<object>(json)); // "My post: 0=a 1=b "
template(JsonNode.Parse(json)); // "My post: 0=a 1=b "

var data = new JsonObject
{
["title"] = "My post",
["tags"] = new JsonArray("a", "b"),
["draft"] = true
};

template(data); // "My post: 0=a 1=b (draft)"
```

For both types:
- Properties are matched by exact name first, then by the lowercase name, so `{{Title}}` finds a `"title"` property.
- Arrays support index access (`{{tags.[0]}}`), `{{tags.Count}}`, and `#each` with `@index`, `@first` and `@last`. Objects support `#each` with `@key`.
- As with other collections, `{{tags.length}}` works once `handlebars.Configuration.UseCollectionMemberAliasProvider()` is enabled.
- `#if`, `#unless` and `#each` treat `false`, `null`, `0`, `""`, `[]` and `{}` as falsy. Pass `includeZero=true` to `#if` to treat `0` as truthy.

When interpolated directly, booleans render as `True`/`False` for `JsonElement` and `true`/`false` for `JsonNode`.

Compatibility: `JsonNode` values `false`, `0`, and `""` now follow falsy semantics; `JsonObject` lookups now include the lowercase fallback described above; custom member alias providers are now consulted for unresolved `JsonElement` and `JsonObject` members.

### Registering Partials

```c#
Expand Down
112 changes: 0 additions & 112 deletions source/Handlebars.Test/DynamicTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text.Json;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

Expand Down Expand Up @@ -301,116 +300,6 @@ public void WithParentIndexJsonNet(IHandlebars handlebars)
Assert.Equal( makeFlat( expected ), makeFlat( result ) );
}

// System.Text.Json's JsonElement (the result of System.Text.Json.JsonSerializer.Deserialize<object>) has no
// built-in support for member access/iteration in .NET, unlike Newtonsoft's JObject/JToken
// above. These tests mirror the JObject coverage to ensure feature parity between the two.
[Fact]
public void JsonElementResolvesNestedProperty()
{
var json = "{\"A\": {\"B\": \"b\"}}";
object data = System.Text.Json.JsonSerializer.Deserialize<object>(json)!;

var template = Handlebars.Create().Compile("{{A.B}}");

Assert.Equal("b", template(data));
}

[Fact]
public void JsonElementRendersScalarPropertyValues()
{
var json = "{\"str\": \"hello\", \"num\": 42, \"nothing\": null}";
object data = System.Text.Json.JsonSerializer.Deserialize<object>(json)!;

var template = Handlebars.Create().Compile("{{str}}|{{num}}|{{nothing}}");

Assert.Equal("hello|42|", template(data));
}

[Fact]
public void JsonElementIteratesArray()
{
var json = "{\"items\": [1, 2, 3]}";
object data = System.Text.Json.JsonSerializer.Deserialize<object>(json)!;

var template = Handlebars.Create().Compile("{{#each items}}{{this}},{{/each}}");

Assert.Equal("1,2,3,", template(data));
}

[Fact]
public void JsonElementIteratesArrayOfObjects()
{
var json = "{\"items\": [{\"Name\": \"a\"}, {\"Name\": \"b\"}]}";
object data = System.Text.Json.JsonSerializer.Deserialize<object>(json)!;

var template = Handlebars.Create().Compile("{{#each items}}{{Name}},{{/each}}");

Assert.Equal("a,b,", template(data));
}

[Fact]
public void JsonElementIteratesObjectProperties()
{
var json = "{\"A\": \"1\", \"B\": \"2\"}";
object data = System.Text.Json.JsonSerializer.Deserialize<object>(json)!;

var template = Handlebars.Create().Compile("{{#each this}}{{@key}}={{this}} {{/each}}");

Assert.Equal("A=1 B=2 ", template(data));
}

[Theory]
[InlineData("{\"flag\": true}", "yes")]
[InlineData("{\"flag\": false}", "no")]
public void JsonElementBooleanRespectsTruthiness(string json, string expected)
{
object data = System.Text.Json.JsonSerializer.Deserialize<object>(json)!;

var template = Handlebars.Create().Compile("{{#if flag}}yes{{else}}no{{/if}}");

Assert.Equal(expected, template(data));
}

[Fact]
public void JsonElementTreatsEmptyStringNullAndZeroAsFalsy()
{
var json = "{\"empty\": \"\", \"nothing\": null, \"zero\": 0}";
object data = System.Text.Json.JsonSerializer.Deserialize<object>(json)!;

var template = Handlebars.Create().Compile(
"{{#if empty}}T{{else}}F{{/if}}" +
"{{#if nothing}}T{{else}}F{{/if}}" +
"{{#if zero}}T{{else}}F{{/if}}"
);

Assert.Equal("FFF", template(data));
}

[Fact]
public void JsonElementTreatsEmptyArrayAndObjectAsFalsy()
{
var json = "{\"emptyArr\": [], \"emptyObj\": {}}";
object data = System.Text.Json.JsonSerializer.Deserialize<object>(json)!;

var template = Handlebars.Create().Compile(
"{{#if emptyArr}}T{{else}}F{{/if}}" +
"{{#if emptyObj}}T{{else}}F{{/if}}"
);

Assert.Equal("FF", template(data));
}

[Fact]
public void JsonElementReturnsEmptyForMissingProperty()
{
var json = "{\"A\": \"a\"}";
object data = System.Text.Json.JsonSerializer.Deserialize<object>(json)!;

var template = Handlebars.Create().Compile("{{Missing.Nested}}");

Assert.Equal("", template(data));
}

#if NET452 || NET46 || NET461 || NET472

[Fact]
Expand Down Expand Up @@ -449,4 +338,3 @@ public override bool TryGetMember(GetMemberBinder binder, out object result)
}
}
}

Loading
Loading