How to get specific block from contentarea of page that may contain contentareas

Vote:
 

Hi peeps!,

Problem:

I have a PageData object.

1. Look for specific block-type in contentarea, on whichever page (PageData) that may have {n} number of contentarea.

2. Parse block(s) from contentarea(s) to IEnumerable (if possible, else retrieve content reference)


Finally, use blocks to create my viewmodels.


Suggestions?

Br,

Jens D.

#198341
Oct 25, 2018 16:58
Vote:
 

Interesting question! This is what I came up with:

public IEnumerable<T> GetAllBlocksOfTypeFromContentAreas<T>(PageData page) where T : BlockData
{
    var results = new List<T>();

    if (page == null) return results;

    foreach (var property in page.Property)
    {
        var contentArea = property.Value as ContentArea;

        if (contentArea == null)
            continue;

        foreach (var contentAreaItem in contentArea.Items)
        {
            T block;
            if (_contentRepository.Service.TryGet(contentAreaItem.ContentLink, out block))
                results.Add(block);
        }
    }

    return results;
}

It does require you to load each piece of content from each ContentArea with the TryGet-call, so it might get a bit heavy performance wise if you have many content areas and many items in those content areas.

Edit: It was hard to name the method in a short and descriptive way. :P

Edit 2: 

Depending on where you're doing this operation you might want personalization and access rights to be considered for picking which content you want to show a specific visitor.

In that case use:

foreach (var contentAreaItem in contentArea.FilteredItems)

instead of

foreach (var contentAreaItem in contentArea.Items)
#198353
Edited, Oct 25, 2018 21:17
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.