C# – Zebra striping built-in to stringtemplate

cstringtemplate

In this example I am striping with code before passing in to the template, I just wanted to make sure I wasn't missing some already built-in stringtemplate functionality.

using System;
using System.Linq;
using Antlr.StringTemplate;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Tests
{
    [TestClass]
    public class RandomTests
    {
        [TestMethod]
        public void has_a_table()
        {
            var users = new[] {
                new { LastName = "Doe", FirstName = "John", Age = 30 },
                new { LastName = "Smith", FirstName = "Bob", Age = 28 }
            };

            var columns = new[] {
                new { Template = "$it.LastName$", Head = "Last Name" },
                new { Template = "$it.FirstName$", Head = "First Name" }
            };

            var tableTemplate = @"
<table>
    <thead>
        <tr>
            <th scope=""col"">Index</th>
            $columns: { column |<th scope=""col"">$colum n.Head$</th>}$
        </tr>
    </thead>
    <tbody>
        $items:{ item |<tr$if(item.Stripe)$ class=""alt""$endif$><td>$i$</td>$item.Item:row()$</tr>}$
    </tbody>
</table>
";
            var rowTemplate = string.Join
            (
                "",
                (from column in columns
                 select
                    "<td>" + column.Template + "</td>"
                ).ToArray()
            );

            var templates = new StringTemplateGroup("table-templator");

            templates.DefineTemplate("table", tableTemplate);
            templates.DefineTemplate("row", rowTemplate);

            var template = templates.GetInstanceOf("table");

            var items = users
                .Select((item, index) => new { Stripe = index % 2 == 0, Item = item })
                .ToArray();

            template.SetAttribute("columns", columns);
            template.SetAttribute("items", items);

            var actual = template.ToString();

            Assert.IsNotNull(actual);
        }

Best Answer

I'm not an expert with StringTemplate, but I found a thread on the mailing list that seems to provide a simpler solution that what you have now.

Related Topic