Listing images located in a specific folder

Published: 10/10/2014, Author: Håkan Edling

An easy way to build image archives is to use folders as a base. This way the content administrator can easily upload images into a specific folder and be confident in that they will show up in the correct place.

Folder name or Id?

The first thing to decide is if you're going to locate the folder by it's name, or simply hardcode it somewhere. If you want to find the folder by name you have to be aware that folder names doesn't have to be unique, so there's always a risk of getting multiple results back.

Updating the model

Let's assume we want a page to display a thumbnail gallery for all of the images within a folder. Let's start off by extending the PageModel and add the image list to it. To make this model & template further reusable, let's assume we've added a property to the PageType named FolderName where the current name of the folder is located. This ensures we can reuse the page type for different galleries.

public class GalleryModel : Piranha.Models.PageModel
public IList<Piranha.Entities.Media> Images { get; set; }

public GalleryModel() : base() {
Images = new List<Piranha.Entities.Media>();

// Loads the images for the
public void LoadImages() {
var folderName = this.Properties.FolderName;

if (!String.IsNullOrWhiteSpace(folderName)) {
using (var db = new Piranha.DataContext()) {
// Get the folder
var folder = db.Media
.Where(m => m.Name == folderName && m.IsFolder)
.Select(m => m.Id)

// Get the images
this.Images = db.Media
.Where(m => m.ParentId == folderId && m.IsImage)
.OrderBy(m => m.Filename)

Now all we have to do is call the method LoadImages on the model after it's loaded in the controller.

Displaying our gallery

Now all we have to render our galler, which is easily acheived with the following code:

<div class="gallery">
@foreach (var image in Model.Images) {
@UI.Thumbnail(image.Id, 80)

blog comments powered by Disqus