I have created a Magento 2 widget that displays a list of categories, similar to the one shown in this guide. The widget outputs the correct HTML, so now I need to add some styling to it to make it look nice.
In my reading on the internet, I have found that I can tell Magento to load a CSS file
- under the
defaultlayout file, which I presume will make it appear on all pages, or - in a layout file that is specific to a single layout handle (for example,
catalog_product_view).
What I am not understanding is how I can tell Magento to ONLY load that CSS file if the widget is present on a given page. Obviously, I can simply hard-code the path to a CSS file in the widget template itself, but this seems hacky. It would also mean that Magento has no way to know to compile/minify that CSS file.
I found a similar question about Magento 1, but the only answer is suggesting to do the exact thing I want to avoid: Having to hard-code the CSS include in the template file.
Disclaimer: Some of my assumptions may be incorrect, so feel free to correct me accordingly.
-
Do you have a solution for this?Akif– Akif2021年04月28日 12:06:20 +00:00Commented Apr 28, 2021 at 12:06
-
No, sorry. In the 4 years since I posted this, I've abandoned Magento entirely and now use Shopify as my platform of choice for new builds.Eric Seastrand– Eric Seastrand2021年04月28日 16:42:17 +00:00Commented Apr 28, 2021 at 16:42
1 Answer 1
Within your custom widget module create the following file:
view/frontend/web/css/source/_extend.less
Add the following code to _extend.less:
@import 'widget/example.less';
Create your .less file here:
view/frontend/web/css/source/widget/example.less