diff --git a/source/Handlebars.Test/IteratorTests.cs b/source/Handlebars.Test/IteratorTests.cs index f60c9f22..069c1025 100644 --- a/source/Handlebars.Test/IteratorTests.cs +++ b/source/Handlebars.Test/IteratorTests.cs @@ -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 { ["name"] = "Erik" }, + 42, + new { name = "Helen" }, + "text", + new Dictionary { ["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 + { + ["a"] = 42, + ["b"] = new Dictionary { ["name"] = "Erik" }, + ["c"] = new List { 1 }, + ["d"] = new { name = "Helen" } + } + }; + var result = template(data); + Assert.Equal("[][Erik][][Helen]", result); + } + [Fact] public void EmptyElementTemplate() { diff --git a/source/Handlebars/BindingContext.cs b/source/Handlebars/BindingContext.cs index 42b1b38b..0866bde4 100644 --- a/source/Handlebars/BindingContext.cs +++ b/source/Handlebars/BindingContext.cs @@ -129,7 +129,19 @@ out WellKnownVariables[(int) WellKnownVariable.Parent] /// 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);