Lucide icons in PHP and Twig (and Craft CMS) #3307
alinnert
started this conversation in
Show and tell
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Here's how to use Lucide icons in a PHP (and potentially Twig) project.
In a nutshell
npm-asset/lucide-staticvia Asset Packagistvendor/npm-asset/lucide-static/icons/{icon-name}.svgInstall dependencies
Setup Asset Packagist
To install packages from Asset Packagist add the following to your
composer.json:{ // Rest of your `composer.json`... "repositories": [ { "type": "composer", "url": "https://asset-packagist.org" } ] }Install
lucide-staticpackageNow you can run
Using Lucide in PHP
The PHP function
Replace
VENDOR_DIRwith the actual path to yourvendordirectory. If you use a PHP framework or CMS you might have different ways to get that path. For Craft CMS you can useCraft::getAlias('@vendor').If it better suits your use-case instead of throwing an exception you can also return a default icon or something else if the requested icon doesn't exist.
Now you can use the function like following. It returns the file content of the SVG file (e.g.
<svg>...</svg>).Using Lucide in Twig
Creating the Twig extension
You can register the function above (with a few changes) as a Twig function like this:
Notice that the function now returns a
\Twig\Markupinstead of astring. This prevents Twig from escaping the SVG code.Use
AsTwigFunctionattribute instead ofgetFunctionsOptionally, you can also use the
AsTwigFunctionattribute (available since Twig 3.21) like below and skip thegetFunctionsfunction but as of this writing Craft CMS ships with Twig 3.15 which doesn't support this attribute yet.Register Twig function
Then you can register this extension in your Twig environment like this:
This might work differently depending on what framework or CMS you're using. For instance, in a Craft CMS module you register your extension like this:
Now you can use this function in Twig like this:
{{ lucide('arrow-right') }}Change options
Now you can change settings like
color,size, andstroke-widthusing CSS:Beta Was this translation helpful? Give feedback.
All reactions