Simple layouts and views with Spark and MonoRail

Yesterday, I wrote about the coolness of The Spark view engine (and a brief history of web programming). As I explore more, I’ll share my experiences here in hope that it shortens other people’s learning curve.

Today’s topic is the basics: writing a simple layout.

Spark offers full support for layouts and views. As with any other view engine, the file extension (by default, .spark) of both your layout and view files must match.

A simple layout looks like this:

<html>
<head>
<title>A simple layout</title>
</head>
<body>
<h1>A simple layout</h1>
<use content="view" />
</body>
</html>

The only thing that isn’t HTML is the <use content="view" /> tag. This tag denotes where in the layout (master template) to embed the content from your view. In NVelocity, we used ${ChildContent} declaration in NVelocity, or the ${ChildOutput} declaration in Brail. Yes, it’s that simple.

Often times, we want to inject some view data into our layout, such as the page title. Let’s say our controller was sending a PageTitle to the view:

public void Simple()
{
PropertyBag["PageTitle"] = "Still a simple sample";
}

How would we get this injected into the title tag in our layout? The quick way is to reference your viewdata, as shown below.

<head>
<title>$!{PropertyBag["PageTitle"]}</title>
</head>

The syntax is similar to that of NVelocity (even the use of the exclamation point to suppress the rendering of nulls), but we’ve got to explicitly reference the PropertyBag. Interestingly, you can also write $!{ViewData["PageTitle"]} — to Spark, both PropertyBag and ViewData are the same. There are two disadvantages with this method:

  1. It’s not as clean as $!{PageTitle}, which we can do in NVelocity.
  2. The result is not strongly-typed, which limits your ability to work easily with complex types.

The solution to these two problems is to specify a Spark viewdata tag and declare the name and type of the view data objects you want to expose. Note the changes in the code below.

<viewdata PageTitle="string" />
<html>
<head>
<title>$!{PageTitle}</title>
</head>

Much cleaner! The Spark web site has an example which shows the use of a strongly-typed collection that illustrates this further.

That’s it for now. It’s just a quick start, but there’s a lot more to Spark, and I highly recommend it to MonoRail users.

0 thoughts on “Simple layouts and views with Spark and MonoRail

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This site uses Akismet to reduce spam. Learn how your comment data is processed.