Orchard Core CMS Decoupled: Displaying an image for a blog post

...

I've been playing around with Orchard Core and Orchard Core CMS recently. It allows you to build a website in three different ways -

  1. fully within the CMS in the same way as a Wordpress site
  2. Decoupled
  3. Headless

I initially intended to write this site in Orchard Core, but got frustrated with the disparity between the documentation and the latest code base. The documentation seems to have caught up now. So I have started work on a website in Orchard Core. The full CMS experience is just a little too restrictive.

Fortunately the decoupled approach allows us to have Orchard Core running the content while leaving the presentation fully in my hands.

Its both surprisingly easy to use and exceedingly time consuming and painful at the same time. A lot of it is really straight forward and some of the How-To guides and samples will help getting stuff done. But they don't go deep enough. The how to guide will show you how to create a decoupled website, how to define content such as a basic blog post within the cms, and then how to render that on a razor page.

Some things though are slightly harder to figure out - such as rendering an image like the one at the top of this post.

Having found how to do it several months ago I knew the info was out there. Eventually I found it about an hour into a 2 hour demo on youtube from 2018. I'd already been through several hours of video and much googling...so instead I'm going to describe the process here.

 

This is relevant as it stands with version 1.0.0-rc2-13450

The orchard core documentation describes how to create a blog post with a Title and Markdown Body - see here for details on that.

Having created a content type of Blog Post - select it from the Content Definition in the left hand menu. Press the edit button to edit it. Click on the Add Field button. Create a field and call it Main Image, of type Media Field.

Save that content type.

When you create a new (or edit an existing) Content Item, you will have a Main Image field which will allow you to select an existing image from the Media Library or upload one.

So far thats all pretty intuitive and  part of the standard CMS stuff.

Whats harder to figure out is how to display that image on a razor page.

The media field picker stores a list of paths to the images selected. It therefore returns an array. Orchard then comes with a helper function to translate that path to a url that can be used as the source of an image. 

The important parts to note are the image source 

src="@Orchard.AssetUrl((string)mainImageSource)"

where mainImageSource is found by

var mainImageSource = blogPost.Content.BlogPost.MainImage.Paths[0];

Obviously you should be checking for existence of an image source. I will be extending this code to allow for multiple images and having them in a carousel if multiple and hiding the image element if there is no image against the blog post.