I have a buddy using Spark on a project and there are some things he was excited to show me earlier today. I asked him to email me an example so I could put up a post about it. It’s especially relevant because earlier in the week a question came up about a case where threaded comments were being rendered in a recursive collection. This is the same type of situation.

A <macro> element in Spark is used to add a function to the generated class. Inside the macro all of the html and output is captured and the function returns it as string. So it can be used in an ${expression}. The function can also call itself, as you can see below.

<viewdata clusterList="List[[Cluster]]" />

$Form.FormTag(new {method="get"});
<p>
  $Form.LabelFor("topic", "Topic:");
  $Form.TextField("topic");
</p>
$Form.EndFormTag();

<style>
    ul.cluster { margin-left:25px; }
</style>

<p if="clusterList != null">
    $displayClusters(clusterList);
</p>

<macro name="displayClusters" clusters="List[[Cluster]]">
    <ul class="cluster">
        <for each="var cluster in clusters">
            <li>$cluster.Name;</li>

            <if condition="cluster.Clusters != null">
                $displayClusters(cluster.Clusters);
            </if>
        </for>
    </ul>
</macro>

This is using the MonoRail version of the Spark view engine of course. You can tell by the use of the Form helper. But that’s a cool example of building a ul-nested li tree where the function string displayClusters(List<Clusters> clusters) is calling itself.

Also note the use of the anonymous type used as an option dictionary in the new {method="get"}. Very nice.