lachr

dies und das

SVG Background Patterns

André
André 5 Apr 22

Create Hero Patterns in Statamic

To create background patterns from an svg like https://heropatterns.com/ I made a custom tag for statamic.

How it's used:

template.antlers.html html
<div
  class="w-full bg-repeat"
  style="{{ bg_pattern src='arrow-pattern' }}">
  <!-- Content goes here -->
</div>

The svg file is stored in /resources/svg/arrow-pattern.svg

Custom Tag

This is the custom tag code. It is copied from the original svg tag form statamic. To generate a Tag class you can follow these instructions.

app/Tags/BgPattern.php php
<?php

namespace App\Tags;

use Statamic\Tags\Tags;
use Statamic\Facades\File;
use Statamic\Facades\URL;
use Statamic\Support\Str;
use Stringy\StaticStringy;

class BgPattern extends Tags
{
    public function wildcard($src)
    {
        $this->params['src'] = $src;

        return $this->index();
    }

    public function index()
    {
        $name = Str::ensureRight($this->params->get('src'), '.svg');

        $cascade = [
            resource_path('svg'),
            resource_path(),
            public_path('svg'),
            public_path(),
        ];

        $svg = null;

        foreach ($cascade as $location) {
            $file = Url::assemble($location, $name);
            if (File::exists($file)) {
                $svg = StaticStringy::collapseWhitespace(
                    File::get($file)
                );
                break;
            }
        }

        return "background-image:url('data:image/svg+xml,".rawurlencode($svg)."');";
    }
}