From 43258937ef93db38901619926af8aca311f65399 Mon Sep 17 00:00:00 2001 From: Mradul Singh Date: Sat, 21 Nov 2026 07:10:30 +0530 Subject: [PATCH] fix: drop cached descriptor when the context value changes type Iterators reuse one BindingContext and only assign Value for each item. The member accessor cached in Descriptor belonged to the first item's type, so a later item of another type threw InvalidCastException (or a later dictionary rendered empty). Reset the descriptor when the value type changes. Fixes #685 --- source/Handlebars.Test/IteratorTests.cs | 39 +++++++++++++++++++++++++ source/Handlebars/BindingContext.cs | 14 ++++++++- 2 files changed, 52 insertions(+), 1 deletion(-) 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);