Use Lucide icons in your Twig templates #17430
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.
-
Note: I've also posted this in the Lucide repository, so this tutorial includes a general instruction how to use Lucide icons in any PHP or Twig project, but it also points out things specific to Craft CMS. It also might work with other icon sets as well.
Here's how to use Lucide icons in a PHP (and potentially Twig) project.
In a nutshell
npm-asset/lucide-static
via Asset Packagistvendor/npm-asset/lucide-static/icons/{icon-name}.svg
Install dependencies
Setup Asset Packagist
To install packages from Asset Packagist add the following to your
composer.json
:Install
lucide-static
packageNow you can run
Using Lucide in PHP
The PHP function
Replace
VENDOR_DIR
with the actual path to yourvendor
directory. 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\Markup
instead of astring
. This prevents Twig from escaping the SVG code.Use
AsTwigFunction
attribute instead ofgetFunctions
Optionally, you can also use the
AsTwigFunction
attribute (available since Twig 3.21) like below and skip thegetFunctions
function 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-width
using CSS:Beta Was this translation helpful? Give feedback.
All reactions