Using the Content Picker in Liquid Templates in Orchard Core CMS

Orchard Core CMS Development

The Content Picker was recently released for Orchard Core CMS. I want to share a tip on how to use the content picker in a Liquid Template (or view), because it's a bit different from how we used it in Orchard CMS (first version of Orchard).

Content Picker for Related Blog Posts

Let's say we have a blog in Orchard Core CMS and we want the ability to select and display content related to each blog post. The Content Picker Field is perfect for this scenario. For simplicity, I will name the field RelatedPosts and restrict the content to other blog posts. However, one could easily call it RelatedItems and allow more than just blog posts to be selected.

Related Blog Posts Orchard Core CMS

Once I have attached the field and configured the editor I can specify related blog posts. It's still new and the look and feel may change, but currently if I create or edit a blog post the editor looks as follows.

Content Picker Field in Orchard Core CMS

Using the Content Picker Field in a Liquid Template

This is the part that may trip you up. The Content Picker in Orchard Core CMS only maintains a list of ContentItemIds, and does not provide a way to retrieve the actual content items. The state is now separate from the behavior. This is different from Orchard CMS where there is a SelectedItems property that allows you to retrieve the content items directly. To retrieve the content items from a Liquid Template, you can use a Liquid Filter.

Let's break this down. First we can retrieve the ContentItemIds for the related blog posts as follows:

{% assign related_post_ids = Model.ContentItem.Content.BlogPost.RelatedPosts.ContentItemIds %}

Now that we have the ContentItemIds we can use a filter, called content_item_id, to obtain the actual content items.

{% assign related_posts = related_post_ids | content_item_id %}

You could do this in 1 step, of course. I just broke it down into 2 steps for clarity.

At this point you have the content items and can loop through the related posts and display the title of each.

{% for related_post in related_posts %}
{{ related_post | display_text }}
{% endfor %}

Documentation

If you're looking for more information, the Orchard Core Documentation is very handy.

I'm a big fan of using Liquid for my views and templates (especially when creating custom themes). You can find the Liquid Documentation here.

Hope you find this handy!