Posts tagged ‘Spark View Engine’

Dynamically Loading Partial Views with the Spark View Engine

Loading a partial view is easy with Spark. There are basically two ways:

<use file="MyPartialView" />
view raw File1.xml This Gist brought to you by GitHub.

And if you have name your files using the _MyPartialView.spark convention:

<MyPartialView />
view raw File2.xml This Gist brought to you by GitHub.

Now what if you don’t know the name of the partial file until runtime and need to dynamically render the view? As far as I know, there is no way of doing this in Spark. How you can get around this is by doing some inline code using ASP.NET MVCs RenderPartial method.

#Html.RenderPartial( myPartialViewVariable );
view raw File3.cs This Gist brought to you by GitHub.

This is assuming myPartialViewVariable is a string variable with the name of the view that needs to be rendered.

Update:

When you use ASP.NET’s Html.RenderPartial, your data isn’t automatically passed along to the spark view. To pass your data along, use the ViewData dictionary, like you would in a controller.

<ul>
    <li each="var item in items">
        #ViewData["item"] = item;
        #Html.RenderPartial( "path/to/" + item.Name );
    </li>
</ul>
view raw File4.xml This Gist brought to you by GitHub.

In the partial view, use the <viewdata /> spark attribute like you normally would in a spark file.

<viewdata item="Item" />
view raw File5.xml This Gist brought to you by GitHub.