Piranha CMS 4.x Custom Blocks for listing blog content

  Kiến thức lập trình

I have been using Piranha CMS 4.x (core 5.3.0) for a while. Pretty neat.

I am trying to create a “Custom Block” that lists latest blog post of certain page by slug or id. Has anybody succeed doing it?

I am not an advanced dotnet player.

You could create a block that uses the PageField that let’s you select a page in the sitemap. Given your block the user should select an ArchivePage and that’s where the posts will be loaded from. You could also add a field for specifying the number of posts to show.

ArchiveBlock.cs

using System;
using Piranha;
using Piranha.Extend;
using Piranha.Extend.Fields;
using Piranha.Models;

namespace RazorWeb.Models.Blocks
{
    [BlockType(Name = "Archive", Category = "Content", Icon = "fas fa-pause")]
    public class ArchiveBlock : Block
    {
        public PageField ArchivePage { get; set; }
        public NumberField NumPosts { get; set; }

        public T GetArchive<T>(IApi api) where T : ArchivePage<T>
        {
            if (ArchivePage.HasValue)
            {
                return api.Archives.GetById<T>(ArchivePage.Id.Value, 1, null, null, NumPosts.Value.HasValue ? NumPosts.Value : 3);
            }
            return null;
        }
    }
}

ArchiveBlock.cshtml

@model RazorWeb.Models.Blocks.ArchiveBlock

<div class="form-group">
    <label>Select Archive</label>
    @Html.EditorFor(m => m.ArchivePage)
</div>
<div class="form-group">
    <label>Set the maximum number of posts</label>
    @Html.EditorFor(m => m.NumPosts)
</div>

And in the DisplayTemplate in the web something like this (change to suit your layout)

ArchiveBlock.cshtml

@model RazorWeb.Models.Blocks.ArchiveBlock
@{
    var archive = Model.GetArchive<RazorWeb.Models.BlogArchive>(WebApp.Api);
}

@foreach (var post in archive.Archive.Posts)
{
    <a href="@post.Permalink"><h1>@post.Title</h1></a>
}

Best regards

LEAVE A COMMENT