2

I have built a custom plugin and have a css file that is being injected as an assetbundle. This works great but when I want to set a background image (SVG in this case) I'm not sure what the path should be. I would like to store the SVG inside the plugin folder and not in the main project. Should I store the SVG in the resources folder or create a web folder like some other plugins seem to do?

2 Answers 2

0

For assets (images, CSS, JS) stored in your plugin's source folder, you'll need a published file URL to use them in front-end or control panel templates.

Essentially, in "publishing" a file, Craft will copy it to the cpresources folder under your web root - meaning that it's eventual URL will be something like https://foo.ddev.site/cpresources/1sdfasz/icon.svg.

Assuming your icon lives in a resources folder inside your plugin, here's how to do it in PHP and Twig, respectively:

$url = \Craft::$app->assetManager->getPublishedUrl(
    '@vendor/plugin/resources/icon.svg',
    true
);
{% set iconUrl = craft.app.assetManager.getPublishedUrl('@vendor/plugin/resources/icon.svg', true) %}

Note that the '@vendor/plugin' part should be replaced with your plugin's auto-generated Yii alias.

See the official docs for more info!

0

I managed to get it working thanks to the awesome Craft CMS support.

As explained in the question I already had my CSS and JS files registered and working in the plugin. The assetbundle's sourcePath is @vendor/plugin_handle/resources/dist/ So I had to move my SVG inside the dist folder.

Then in the css file I just had to adjust the path to the SVG relative to the css file. In my case it was ../img/icon.svg

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.