ideas icon indicating copy to clipboard operation
ideas copied to clipboard

Icon Fieldtype Augmentation (SVG Tag Support)

Open jnbn opened this issue 1 year ago • 1 comments

I think many users may need or expect icon field type to act like an SVG tag by default. Or may need to use the path of the file in an svg tag.

But as the current augmentation returns the SVG file contents directly it's not possible to use extra classes etc with the required stylings on the front end.

public function augment($value)
    {
        [$path] = $this->resolveParts();
        // return ($path.'/'.$value.'.svg');

        return File::get($path.'/'.$value.'.svg');
    }

jnbn avatar Feb 05 '25 02:02 jnbn

Sample file. which can be used like:

{{ svg :src="iconFieldName" class="size-8" }}

<?php

namespace App\Fieldtypes;

use Statamic\Fieldtypes\Icon;

use Statamic\Facades\File;
use Statamic\Facades\Folder;
use Statamic\Facades\Path;
use Statamic\Fields\Fieldtype;
use Statamic\Support\Str;


class SvgIcon extends Icon
{

    /**
     * Augment the value for frontend use
     */
    public function augment($value)
    {
        [$path] = $this->resolveParts();

        return ($path.'/'.$value.'.svg');
    }

    private function resolveParts()
    {
        $hasConfiguredDirectory = true;

        if (! $directory = $this->config('directory')) {
            $hasConfiguredDirectory = false;
            $directory = statamic_path('resources/svg/icons');
        }

        $folder = $this->config(
            'folder',
            $hasConfiguredDirectory ? null : self::DEFAULT_FOLDER 
        );

        // ADDED: remove resources/svg or resources/ from the beginning
        $directory = Str::startsWith($directory, 'resources/svg') ? Str::after($directory, 'resources/svg') : Str::after($directory, 'resources/');

        $path = Path::tidy($directory.'/'.$folder);

        return [
            $path,
            $directory,
            $folder,
            $hasConfiguredDirectory,
        ];
    }
} 

jnbn avatar Feb 05 '25 03:02 jnbn