Custom Blocks

Last Updated: 2019-01-22

If you want to read more about the blocks included in Piranha, please refer to Standard Blocks´╗┐.

Blocks are the content pieces that the Administrators can use when designing the main content body. They main difference between Fields and Blocks is that blocks are intended to be more visual in their presentation than fields to give editors a clear understanding of the content they are creating.

Create The Block

A block is in essence a class that inherits from the abstract base class Piranha.Extend.Block. A block can contain one or several fields, it can actually contain data that is not a field as well, but only fields that derive from Piranha.Extend.IField will be saved in the database. All blocks need to be marked with the BlockType attribute.

As an example, let's take a look at how the Quote block is implemented.

using Piranha.Extend;
using Piranha.Extend.Fields;

[BlockType(Name = "Quote", Category = "Content", Icon = "fas fa-quote-right")]
public class QuoteBlock : Block
{
/// <summary>
/// Gets/sets the text body.
/// </summary>
public TextField Body { get; set; }
}

BlockType Attribute

In order to register your block you need to mark it with the BlockType attribute like in the above example. This has the following properties.

Name

public string Name { get; set; }

This is the name that is shown in the manager interface when editing.

Category

public string Category { get; set; }

The name of category the Block will be grouped under in the manager interface.

Icon

public string Icon { get; set; }

Css class for rendering the Block icon in the manager interface. The manager interface uses the free icon package from font awesome.

IsUnlisted

public bool IsUnlisted { get; set; }

If you're developing a block that is supposed to be used within a Block Group you should set this to true. This will prevent it from being shown elsewhere when adding Blocks.

Register The Block

All available blocks has to be registered in the singleton Piranha.App after the app has been initialized.

Piranha.App.Init(api);

// Register custom blocks
Piranha.App.Blocks.Register<MyCustomBlock>();

Create the manager view

The manager interface is based on EditorTemplates for each block. All views for blocks should be placed in:

~/Areas/Manager/Views/Shared/EditorTemplates

with the same name as the block class, in this example it should be named QuoteBlock.cshtml.

@model Piranha.Extend.Blocks.QuoteBlock
@{
var prefix = Html.ViewData.TemplateInfo.HtmlFieldPrefix
.Replace("[", "_").Replace("]", "_").Replace(".", "_");
}

@Html.HiddenFor(m => m.Body.Value, "")
<div class="content-preview">
<blockquote>
<div class="editor-area" contenteditable="true" data-id="@(prefix)_Body_Value">
@if (!string.IsNullOrWhiteSpace(Model.Body.Value))
{
@Html.Raw(Model.Body.Value)
}
else
{
<text>&nbsp;</text>
}
</div>
</blockquote>
</div>