Contribute to Docs Contribute to Docs

Previewing

Piranha CMS provides functionality for previewing content before publishing it, however, you will need to provide support for this in your controllers and views.

When content is added or changed in the Piranha CMS Manager, the changes are saved as a draft while you are modifying the content. Once you have completed the modifications you can publish to make those changes show up on your web page. Previewing allows you to see your content draft before it has been published.

When previewing the content the Piranha middleware that handles the request will set a query parameter indicating whether the content being requested is a draft or the published version. You can accept this parameter in your route to retrieve the draft model and return it to your view instead of the live version.

Assume we are attempting to preview an archive page. We can do that with the MVC module like this:

[Route("/page")]
public async Task<IActionResult> GetPage(Guid id, int? year = null, int? month = null,
    int? page = null, Guid? category = null, Guid? tag = null, bool draft = false)
{
    SimpleArchivePage pageModel = null;
    if(draft)
    {
        pageModel = await _api.Pages.GetDraftByIdAsync<SimpleArchivePage>(id);
    }

    // if the draft is true but this is null that means there were no changes
    // and we are simply previewing the live version
    if(pageModel == null)
    {
        pageModel = await _api.Pages.GetByIdAsync<SimpleArchivePage>(id);
    }

    pageModel.Archive = await _api.Archives.GetByIdAsync<SimplePost>(id);
    return View(pageModel);
}

In some cases, your preview may need to reference a different Razor view than your live model. For instance, when previewing a post you may not want all of the header/footer information to be included but only the post information. You can use the draft parameter to choose which view is returned.

if(draft)
{
    return View("/Views/CustomPreview.cshtml", postModel);
}
else
{
    return View(postModel);
}