Skip to content

Custom Templates

Clark Winkelmann edited this page May 4, 2021 · 4 revisions

You can create custom templates for FoF Upload.

⚠️ Custom templates are broken since the Media Manager was added. See https://github.com/FriendsOfFlarum/upload/issues/281

Two interfaces are available:

  • FoF\Upload\Contracts\Template: the base interface for templates.
  • FoF\Upload\Contracts\TextFormatterTemplate: an additional interface for templates that want to register a bbcode in TextFormatter. We recommend you not use this and instead register your bbcode manually to minimize the risk of breaking changes.

The Template interface contains:

  • tag is a unique identifier used in the settings and saved alongside each file in the database. When used together with the TextFormatterTemplate interface, it's also used as the TextFormatter internal tag name. To future-proof your code, don't use an identifier that's also used internally by TextFormatter, like img or a.
  • name and description are used by the admin panel.
  • preview is the text inserted in the editor once the file is successfully uploaded.

Templates can be registered by calling FoF\Upload\Helpers\Util::addRenderTemplate from a service provider.

The code below shows an example where we insert an image using bbcode that's already added by another extension (in this case, the bbcode extension). This code could be part of an extension or added to the local extend.php of your forum.

<?php

use Flarum\Extend;
use Flarum\Foundation\AbstractServiceProvider;
use FoF\Upload\Contracts\Template;
use FoF\Upload\File;
use FoF\Upload\Helpers\Util;

class MyTemplate implements Template
{
    public function tag(): string
    {
        return 'myuniquetemplatename';
    }

    public function name(): string
    {
        return 'My template name in the admin panel';
    }

    public function description(): string
    {
        return 'A description of the template that appears in the admin panel';
    }

    public function preview(File $file): string
    {
        return '[img]' . $file->url . '[/img]';
    }
}

class MyServiceProvider extends AbstractServiceProvider
{
    public function register()
    {
        $this->container->make(Util::class)->addRenderTemplate($this->container->make(MyTemplate::class));
    }
}

return [
    (new Extend\ServiceProvider())
        ->register(MyServiceProvider::class),
];
Clone this wiki locally