Jul 23, 202011:12 AM - edited Jul 23, 202011:18 AM
Member
HubL doesn't parse in CSS files?
SOLVE
I'm working on a module right now which requires me to use different CSS rules according to which fields of the module are being used. My plan was to use HubL for a basic if/else control structure in the CSS file.
I thought I would be able to do this based on the fact that there are several examples of using HubL with CSS in the HubL documentation itself. For example, HubL Syntax, where the following example, among others, is shown:
{% set primaryColor = '#F7761F' %} {# defines variable and assigns HEX color #}
a {
color: {{ primaryColor }}; {# prints variable HEX value #}
}
But as soon as I tried to do it, I got a warning that "HubL in your CSS or JavaScript won’t be parsed, except for the module_asset_url function" and, indeed, the HubL didn't parse, it came through to the client side still sitting in the CSS file.
This is the relevent section of my module.css file:
So I'm a bit confused. Can HubL be used with CSS or not? If not, why not, and why does the documentation include several examples of using HubL with CSS?
Another way to add styles into your module.html file is by using
{% require_css %} and {% end_require_css %}
This can make your output html cleaner. For example:
{% require_css %}
/* name will get the name of the module row (this is unique) */
<style id="{{ name ~ '__styles'}}">
/* create a class using an ID dynamically based on the module row name */
{{ '#EXAMPLEIDSELECTOR--target_' ~ name }} {
color: {{ module.primaryColor.color }}
}
</style>
{% end_require_css %}
This code then appears in your HEAD having created a new class for each row
your row then needs to match with it's ID and that's easily done like so:
<div id="{{'EXAMPLEIDSELECTOR--target_' ~ name }}">
...
...
...
...
</div>
This way is cleaner html, but most of the time it doesn't matter which way it's done 🙂
ps, I learnt this from reading HubSpots code on their modules. You learn a lot from them 🙂