Copied to clipboard

Flag this post as spam?

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


  • Mikael Axel Kleinwort 140 posts 484 karma points c-trib
    Apr 24, 2021 @ 10:19
    Mikael Axel Kleinwort
    0

    Get list of properties of a specific type on a page

    In Umbraco 8, I have a page with several properties. Some of the properties are blocklists. Now I want to get a list of the blocklists on the page.

    What I have come up with - and what works - is this approach. MyPage is of type IPublishedContent:

    var blockListsOnMyPage = 
        MyPage.Properties
            .Where(p => p.PropertyType.ClrType.Name == "BlockListModel")
            .Select(p => (BlockListModel)p.GetValue());
    

    This works but it looks rather hacky to me. Is this the proper approach?

    The page in question (MyPage) is of a specific data type. So I could also query based on the page's data type rather than actual content.

    I would like to learn the correct Umbraco ways and I am grateful for some guidance. Thank you very much!

  • Marc Goodson 2141 posts 14344 karma points MVP 8x c-trib
    Apr 25, 2021 @ 20:04
    Marc Goodson
    0

    Hi Mikael

    It would be unusual to need to loop through all the properties of a Document Type for a page, in order to display the contents of each of the Block List Editors you have configured in a particular template... but I might be misunderstanding and you might have a specific requirement.

    Generally though, you'll know the Document Type for the page you are building the template for, so you'll know which Block List Editors are on that page, and each one will have their own property alias. You'll probably want to write out the blocks from each block list editor in different parts of the template.

    There is some info here are rendering BlockListEditor content:

    https://our.umbraco.com/documentation/getting-started/backoffice/property-editors/built-in-property-editors/Block-List-Editor/#rendering-block-list-content

    But essentially you'd simplistically have something like this

    <div class="homepage-blocks" >
     @Html.GetBlockListHtml(Model, "homepageBlocks")
    </div>
    

    where homepageBlocks is the alias of the Block List Editor.

    If you want to wrap custom markup around each 'block' you could instead get a reference to each block and write them out separately using a partial view for each block by 'block type'

    @inherits Umbraco.Web.Mvc.UmbracoViewPage
    @using Umbraco.Core.Models.Blocks;
    @{
        var blocks = Model.Value<IEnumerable<BlockListItem>>("homepageBlocks");
        foreach (var block in blocks)
        {
            var content = block.Content;
    
            @Html.Partial("HomepageBlocksFolder/" + content.ContentType.Alias, block)
        }
    }
    

    regards

    Marc

Please Sign in or register to post replies

Write your reply to:

Draft