Custom Blocks

Håkan Edling edited this page Jul 10, 2018 · 2 revisions

Blocks are content pieces that the Administrators can use when designing the content of the pages. For general information about the different data types available when building content, please refer to Content Type Anatomy.

Create the Block

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>
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.