diff --git a/docs/for-developers/quick-start.md b/docs/for-developers/quick-start.md index 77fa653..1a132d6 100644 --- a/docs/for-developers/quick-start.md +++ b/docs/for-developers/quick-start.md @@ -241,7 +241,9 @@ Console.WriteLine(string.Join(", ", validation.MissingVariables)); Each missing variable or loop collection is reported as an error of type `MissingVariable` (so `IsValid` is `false` for that data) and listed in `MissingVariables`; call `ValidateTemplate(template)` without data to check -the syntax only. `validation.Warnings` reports loops over empty collections (`EmptyLoopCollection`, controlled by +the syntax only. Inside a loop, the whole path of an item (`{{line.product.name}}`) is checked against the loop's +items: it counts as present when at least one item has it (a `null` on the way counts too), otherwise the outer +scopes and the data are tried, as processing does. `validation.Warnings` reports loops over empty collections (`EmptyLoopCollection`, controlled by `WarnOnEmptyLoopCollections`), condition keywords used as variable names (`ReservedWordAsVariable`) and conditions that test a variable missing from the data on its own (`MissingConditionVariable`, see below). Warnings never make `IsValid` false. diff --git a/src/TriasDev.Templify/Core/ScopedVariableValidator.cs b/src/TriasDev.Templify/Core/ScopedVariableValidator.cs index 3cd2dd3..966414e 100644 --- a/src/TriasDev.Templify/Core/ScopedVariableValidator.cs +++ b/src/TriasDev.Templify/Core/ScopedVariableValidator.cs @@ -397,10 +397,9 @@ private bool CanResolveInScope(string placeholder) } // Property access via the named iteration variable (e.g., {{item.Name}}) or implicit - // property access (e.g., {{Name}}, {{Address.City}}). - // Note: During static validation, only the root property is verified against the loop items; - // runtime processing reports invalid nested paths. - if (GetPathRelativeToScope(placeholder, scope) != null) + // property access (e.g., {{Name}}, {{Address.City}}): the whole path must resolve on an item + // (#299). Otherwise processing falls back to the outer scopes, and so does validation. + if (GetPathRelativeToScope(placeholder, scope) is { } relativePath && ResolvesOnAnItem(relativePath, scope.Items)) { return true; } @@ -410,6 +409,21 @@ private bool CanResolveInScope(string placeholder) return _resolver.TryResolveValue(_data, placeholder, out _); } + /// + /// Whether a path relative to the loop items resolves on at least one item. A null on the way counts as present + /// (the item has the property, its value is empty), as in processing. + /// + internal static bool ResolvesOnAnItem(string relativePath, IReadOnlyList items) + { + if (relativePath.IndexOfAny(['.', '[']) < 0 || !PropertyPath.TryParse(relativePath, out PropertyPath? path) || path == null) + { + // One segment: the aggregated item properties already hold it. + return true; + } + + return items.Any(item => item != null && PropertyPathResolver.TryResolvePath(item, path, out _)); + } + private static IReadOnlyList DetectLoops(IReadOnlyList elements) { try diff --git a/src/TriasDev.Templify/OpenDocument/OdtTemplateValidator.cs b/src/TriasDev.Templify/OpenDocument/OdtTemplateValidator.cs index ca76b3d..73b6080 100644 --- a/src/TriasDev.Templify/OpenDocument/OdtTemplateValidator.cs +++ b/src/TriasDev.Templify/OpenDocument/OdtTemplateValidator.cs @@ -765,7 +765,9 @@ private bool CanResolveInScope(string placeholder) { foreach (LoopScope scope in _loopStack) { - if (placeholder == scope.IterationVariableName || GetPathRelativeToScope(placeholder, scope) != null) + // The whole path must resolve on an item (#299); otherwise the outer scopes are tried, as in processing. + if (placeholder == scope.IterationVariableName + || (GetPathRelativeToScope(placeholder, scope) is { } relativePath && ScopedVariableValidator.ResolvesOnAnItem(relativePath, scope.Items))) { return true; } diff --git a/tests/TriasDev.Templify.Tests/Core/LoopItemPathValidationTests.cs b/tests/TriasDev.Templify.Tests/Core/LoopItemPathValidationTests.cs new file mode 100644 index 0000000..c7df73e --- /dev/null +++ b/tests/TriasDev.Templify.Tests/Core/LoopItemPathValidationTests.cs @@ -0,0 +1,95 @@ +// Copyright (c) 2026 TriasDev GmbH & Co. KG +// Licensed under the MIT License. See LICENSE file in the project root for full license information. + +using TriasDev.Templify.Core; +using TriasDev.Templify.Tests.Helpers; + +namespace TriasDev.Templify.Tests.Core; + +/// +/// #299: with data, validation resolves the whole path of a loop item (not only its first segment), for values and +/// condition variables, in DOCX and ODT. A path counts as present when any item has it; a null on the way is present. +/// +public sealed class LoopItemPathValidationTests +{ + public static TheoryData Formats => new TheoryData("docx", "odt"); + + private static Dictionary Data() => new Dictionary + { + ["lines"] = new List> + { + new() { ["product"] = new Dictionary { ["name"] = "p" }, ["note"] = null, ["tags"] = new List { "t" } }, + new() { ["product"] = new Dictionary { ["name"] = "q", ["sku"] = "s" } }, + }, + ["config"] = new Dictionary { ["limit"] = 3 }, + ["json"] = System.Text.Json.JsonDocument.Parse("""{ "rows": [ { "cell": { "value": 1 } } ] }""").RootElement, + }; + + private static ValidationResult Validate(string format, params string[] paragraphs) + { + if (format == "docx") + { + DocumentBuilder docx = new DocumentBuilder(); + foreach (string paragraph in paragraphs) + { + docx.AddParagraph(paragraph); + } + + using MemoryStream stream = docx.ToStream(); + return new DocumentTemplateProcessor().ValidateTemplate(stream, Data()); + } + + OdtDocumentBuilder odt = new OdtDocumentBuilder(); + foreach (string paragraph in paragraphs) + { + odt.AddParagraph(paragraph); + } + + using MemoryStream odtStream = new MemoryStream(odt.ToBytes()); + return new OdtTemplateProcessor().ValidateTemplate(odtStream, Data()); + } + + [Theory] + [MemberData(nameof(Formats))] + public void NamedItem_MissingNestedValue_IsMissing(string format) => + Assert.Equal(new[] { "line.product.removed" }, Validate(format, "{{#foreach line in lines}}", "{{line.product.removed}}", "{{/foreach}}").MissingVariables); + + [Theory] + [MemberData(nameof(Formats))] + public void NamedItem_MissingNestedConditionVariable_IsWarned(string format) + { + // A missing condition variable is a warning (the condition is false), as for top-level paths. + ValidationResult result = Validate(format, "{{#foreach line in lines}}", "{{#if line.product.removed}}", "x", "{{/if}}", "{{/foreach}}"); + Assert.Contains(result.Warnings, w => w.Type == ValidationWarningType.MissingConditionVariable && w.Message.Contains("line.product.removed", StringComparison.Ordinal)); + } + + [Theory] + [MemberData(nameof(Formats))] + public void ImplicitItem_MissingNestedValue_IsMissing(string format) => + Assert.Equal(new[] { "product.removed" }, Validate(format, "{{#foreach lines}}", "{{product.name}} {{product.removed}}", "{{/foreach}}").MissingVariables); + + [Theory] + [MemberData(nameof(Formats))] + public void PresentInAnyItem_IsPresent(string format) + { + ValidationResult result = Validate(format, "{{#foreach line in lines}}", "{{line.product.name}} {{line.product.sku}} {{line.tags[0]}}", "{{#if line.product.sku}}", "x", "{{/if}}", "{{/foreach}}"); + Assert.Empty(result.MissingVariables); + Assert.DoesNotContain(result.Warnings, w => w.Type == ValidationWarningType.MissingConditionVariable); + Assert.True(result.IsValid); + } + + [Theory] + [MemberData(nameof(Formats))] + public void NullOnTheWay_IsPresent(string format) => + Assert.Empty(Validate(format, "{{#foreach line in lines}}", "{{line.note.text}}", "{{/foreach}}").MissingVariables); + + [Theory] + [MemberData(nameof(Formats))] + public void ImplicitPath_NotOnTheItem_FallsBackToTheData(string format) => + Assert.Empty(Validate(format, "{{#foreach lines}}", "{{config.limit}}", "{{/foreach}}").MissingVariables); + + [Theory] + [MemberData(nameof(Formats))] + public void JsonItems_MissingNestedValue_IsMissing(string format) => + Assert.Equal(new[] { "row.cell.nope" }, Validate(format, "{{#foreach row in json.rows}}", "{{row.cell.value}} {{row.cell.nope}}", "{{/foreach}}").MissingVariables); +} diff --git a/tests/TriasDev.Templify.Tests/Odt/OdtValidationParityTests.cs b/tests/TriasDev.Templify.Tests/Odt/OdtValidationParityTests.cs index 5cd732c..7e0ae1a 100644 --- a/tests/TriasDev.Templify.Tests/Odt/OdtValidationParityTests.cs +++ b/tests/TriasDev.Templify.Tests/Odt/OdtValidationParityTests.cs @@ -71,6 +71,7 @@ public sealed class OdtValidationParityTests { "orphan else and elseif", new[] { "{{#else}}", "x", "{{#elseif B}}" } }, { "nested end markers in loop", new[] { "{{#foreach Items}}", "{{#if A}}", "{{Title}}", "{{/if}}{{/foreach}}" } }, { "text next to nested markers", new[] { "{{#foreach Items}}", "Sub: {{#if Active}}", "{{Title}}", "{{/if}}", "{{/foreach}}" } }, + { "nested item paths (#299)", new[] { "{{#foreach item in Items}}", "{{item.Details.Code}} {{item.Details.Nope}} {{Details.Nope}}", "{{#if item.Details.Nope}}", "x", "{{/if}}", "{{/foreach}}" } }, }; [Theory] @@ -126,7 +127,7 @@ private static List Describe(IEnumerable errors) => ["List"] = new List { "a" }, ["Items"] = new List> { - new() { ["Title"] = "i1", ["Active"] = true }, + new() { ["Title"] = "i1", ["Active"] = true, ["Details"] = new Dictionary { ["Code"] = "d" } }, new() { ["Title"] = "i2" }, }, ["Categories"] = new List>