How to place your component presentations by view or region in DD4T

I’ve recently spent some time looking at the DD4T framework, which provides MVC support for Tridion-based web applications. The concepts remain familiar to anyone who’s worked with the various templating frameworks on the Content Manager. You render a page, although now the output is defined by a view instead of a page template. In the page are component presentations, and DD4T allows you to render them with views that fulfil the same role as component templates. The standard approach is simply to map component templates to these views. The framework has support for creating ViewModel objects and declaratively indicating their relationship with the content model published from Tridion. This makes it easy to get a ViewModel for your page and also for each of its component presentations.

I’d been following Katarina Stojanovski’s blog post about using ViewModels in DD4T, and as a starting point, I had used the [ComponentPresentations] attribute to have the framework automatically add the component presentations to my page view model:

Then in my page view, I wanted to put particular kinds of content in specific places on the page, so filter the component presentations. The first time I tried this it was with a Linq expression:

This works, but it’s letting the code leak into the view, so you’d want to keep it to a minimum. So then I tried putting the logic back in the Model by exposing a separate List like this

And so now you can access it via cleaner code in the view, like this:

Then having got all this working, I revisited Katarina’s blog post, and saw that she mentions this:

There are a few more attributes available for mapping component presentations, like PresentationsByView and PresentationsByRegion, which filter components presentations by view and region name respectively. Both of these filters can be defined in the component template metadata.

So with my new-found understanding I now realised what she was getting at. The framework provides these attributes to save you having to write the filtering code yourself. So now the code boils down to the following:

This assumes that in your component template metadata you have a field called “view”, and that your ViewPrefix parameter matches. The match is done using String.StartsWith() so you could use naming conventions to group items with different component templates. The other attribute; PresentationsByRegion works in exactly the same way, but relies on a metadata field called “region”.  (You can find the code for both of these attributes here.)

The framework support for View Models is very useful, and as you can see, it can considerably reduce the amount of code you’d otherwise write.