Skip to content
Closed
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
39 changes: 39 additions & 0 deletions source/Handlebars.Test/IteratorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,45 @@ public void BasicIterator()
Assert.Equal("Hello,\n- Erik\n- Helen", result);
}

[Fact]
public void IteratorWithItemsOfDifferentTypes()
{
var source = "{{#each items}}[{{name}}]{{/each}}";
var template = Handlebars.Create().Compile(source);
var data = new
{
items = new object[]
{
new Dictionary<string, object> { ["name"] = "Erik" },
42,
new { name = "Helen" },
"text",
new Dictionary<string, object> { ["name"] = "Ann" }
}
};
var result = template(data);
Assert.Equal("[Erik][][Helen][][Ann]", result);
}

[Fact]
public void ObjectIteratorWithValuesOfDifferentTypes()
{
var source = "{{#each items}}[{{name}}]{{/each}}";
var template = Handlebars.Create().Compile(source);
var data = new
{
items = new Dictionary<string, object>
{
["a"] = 42,
["b"] = new Dictionary<string, object> { ["name"] = "Erik" },
["c"] = new List<object> { 1 },
["d"] = new { name = "Helen" }
}
};
var result = template(data);
Assert.Equal("[][Erik][][Helen]", result);
}

[Fact]
public void EmptyElementTemplate()
{
Expand Down
14 changes: 13 additions & 1 deletion source/Handlebars/BindingContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,19 @@ out WellKnownVariables[(int) WellKnownVariable.Parent]
/// </summary>
internal bool HasFrameHelpers { get; set; }

public object? Value { get; set; }
private object? _value;

public object? Value
{
get => _value;
set
{
// Iterators reuse one context for every item. The cached descriptor depends on the
// value's type, so it has to be dropped when an item of another type comes in.
if (_value?.GetType() != value?.GetType()) Descriptor.Reset();
_value = value;
}
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
public BlockParamsValues BlockParams(ChainSegment[] blockParamsVariables) => new BlockParamsValues(this, blockParamsVariables);
Expand Down
Loading