Skip to content

Commit

Permalink
Do not render DynamicTable without any header values
Browse files Browse the repository at this point in the history
  • Loading branch information
Amberg committed Feb 5, 2024
1 parent 31d0fc9 commit 6aef5f2
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
19 changes: 19 additions & 0 deletions DocxTemplater.Test/DocxTemplateTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,24 @@ public void DynamicTable()
Assert.That(rows[4].InnerText, Is.EqualTo("Value7Value8Value9"));
}

[Test]
public void EmptyDynamicTable()
{
using var fileStream = File.OpenRead("Resources/DynamicTable.docx");
var docTemplate = new DocxTemplate(fileStream);
var tableModel = new DynamicTable();
docTemplate.BindModel("ds", tableModel);
var result = docTemplate.Process();
docTemplate.Validate();
result.Position = 0;
result.SaveAsFileAndOpenInWord();
result.Position = 0;
var document = WordprocessingDocument.Open(result, false);
var body = document.MainDocumentPart.Document.Body;
var table = body.Descendants<Table>().FirstOrDefault();
Assert.That(table, Is.Null);
}

/// <summary>
/// Dynamic tables are only required if the number of columns is not known at design time.
/// otherwise a simple table bound to a collection of objects is sufficient.
Expand Down Expand Up @@ -321,6 +339,7 @@ public void CollectionSeparatorTest()
Assert.That(body.InnerText, Is.EqualTo("Item1,Item2,Item3"));
}


[Test]
public void ConditionsWithAndWithoutPrefix()
{
Expand Down
6 changes: 5 additions & 1 deletion DocxTemplater/Blocks/DynamicTableBlock.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ public override void Expand(ModelLookup models, OpenXmlElement parentNode)
var model = models.GetValue(m_tablenName);
if (model is IDynamicTable dynamicTable)
{
if (!dynamicTable.Headers.Any())
{
return;
}

var headersName = $"{m_tablenName}.{nameof(IDynamicTable.Headers)}";
var columnsName = $"{m_tablenName}.{nameof(IDynamicTable.Rows)}";
Expand Down Expand Up @@ -74,7 +78,7 @@ public override void Expand(ModelLookup models, OpenXmlElement parentNode)
dataCell.Remove();

// ensure all rows have the same number of cells
var maxCells = dynamicTable.Rows.Max(r => r.Count());
var maxCells = dynamicTable.Rows.DefaultIfEmpty().Max(r => r?.Count() ?? 0);
foreach (var row in table.Elements<TableRow>())
{
var cells = row.Elements<TableCell>().ToList();
Expand Down

0 comments on commit 6aef5f2

Please sign in to comment.