Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Peter van den Dungen 65 posts 363 karma points
    Nov 28, 2022 @ 16:53
    Peter van den Dungen
    0

    Perplex ContentBlocks: Determine in masterpage what kind of content blocks are used

    Hi Daniël,

    On the masterpage we want to determine what type of content blocks are used for the loaded page.

    Now I have this extension method, but I think it can be done without reflection.

    public static bool HasDealerLocatorContentBlock(this IPublishedContent content)
        {
            var contentBlocks = content
                .GetType()?
                .GetProperties()?
                .FirstOrDefault(x => x.Name == nameof(Perplex.ContentBlocks.Rendering.ContentBlocks))?
                .GetValue(content, null);
    
            if (contentBlocks != null && contentBlocks is Perplex.ContentBlocks.Rendering.IContentBlocks)
            {
                if ((contentBlocks as Perplex.ContentBlocks.Rendering.IContentBlocks).Blocks.Any(x => x.Content is DealerLocatorBlock))
                {
                    return true;
                }
            }
    
            return false;
        }
    
  • Daniël Knippers 144 posts 1084 karma points MVP 2x c-trib
    Nov 30, 2022 @ 07:21
    Daniël Knippers
    100

    Hi Peter,

    You indeed do not need reflection, you can enumerate all properties of IPublishedContent with their own API. So your method could probably be written like this (untested code though):

    public static bool HasDealerLocatorContentBlock(this IPublishedContent content)
    {
        if(content is null)
        {
            return false;
        }
    
        foreach (var property in content.Properties)
        {
            if (property.PropertyType.EditorAlias == Perplex.ContentBlocks.Constants.PropertyEditor.Alias &&
                content.Value<IContentBlocks>(property.Alias) is IContentBlocks contentBlocks &&
                contentBlocks.Blocks.Any(b => b.Content is DealerLocatorBlock))
            {
                return true;
            }
        }
    
        return false;
    }
    
  • Peter van den Dungen 65 posts 363 karma points
    Nov 30, 2022 @ 07:55
    Peter van den Dungen
    0

    Thanks Daniël!

Please Sign in or register to post replies

Write your reply to:

Draft