Skip to content
Merged
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
4 changes: 3 additions & 1 deletion docs/for-developers/quick-start.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
22 changes: 18 additions & 4 deletions src/TriasDev.Templify/Core/ScopedVariableValidator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand All @@ -410,6 +409,21 @@ private bool CanResolveInScope(string placeholder)
return _resolver.TryResolveValue(_data, placeholder, out _);
}

/// <summary>
/// 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.
/// </summary>
internal static bool ResolvesOnAnItem(string relativePath, IReadOnlyList<object?> 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<LoopBlock> DetectLoops(IReadOnlyList<OpenXmlElement> elements)
{
try
Expand Down
4 changes: 3 additions & 1 deletion src/TriasDev.Templify/OpenDocument/OdtTemplateValidator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
95 changes: 95 additions & 0 deletions tests/TriasDev.Templify.Tests/Core/LoopItemPathValidationTests.cs
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// #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.
/// </summary>
public sealed class LoopItemPathValidationTests
{
public static TheoryData<string> Formats => new TheoryData<string>("docx", "odt");

private static Dictionary<string, object> Data() => new Dictionary<string, object>
{
["lines"] = new List<Dictionary<string, object?>>
{
new() { ["product"] = new Dictionary<string, object> { ["name"] = "p" }, ["note"] = null, ["tags"] = new List<string> { "t" } },
new() { ["product"] = new Dictionary<string, object> { ["name"] = "q", ["sku"] = "s" } },
},
["config"] = new Dictionary<string, object> { ["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);
}
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down Expand Up @@ -126,7 +127,7 @@ private static List<string> Describe(IEnumerable<ValidationError> errors) =>
["List"] = new List<string> { "a" },
["Items"] = new List<Dictionary<string, object>>
{
new() { ["Title"] = "i1", ["Active"] = true },
new() { ["Title"] = "i1", ["Active"] = true, ["Details"] = new Dictionary<string, object> { ["Code"] = "d" } },
new() { ["Title"] = "i2" },
},
["Categories"] = new List<Dictionary<string, object>>
Expand Down
Loading