HubL - Any way to get the id of the module instance?

When the custom module is rendered, an unique id is attached to the HTML div component with the format hs_cos_wrapper_widget_1538643526593

Is there a way to get this unique ID in the module itself through HUBL?

Basically I’m looking for a way to identify the very instance of the module in template to assign media-query specific CSS. Class alone is not unique enough for our use-case.

Appreciate any insight! :slightly_smiling_face:

Hey @yidanwang I believe that you can access that using the {{ name }} variable in HubL within the custom module. Here is an example where I used the variable in my code:

And the output that I received in the HTML as a result:

So in your case you might need something like:

.hs_cos_wrapper_{{name}} {

}

Please note that HubL can only be used in the HTML pane of the custom module editor so you might need to put your CSS in some <style> tags in the HTML pane and wrap that in {% require_css %}{% end_require_css %}

WORKS LIKE A CHARM! Thank you SO MUCH, Jason! This saves my world!

One minor twist to your answer: the css selector is # (Id selector), not class selector :slightly_smiling_face:

Hey @yidanwang I’m happy to hear this is working for you! Also, good catch on the ID
16x16_smiley-happy.png.png
!

Hi Jason,

I tried placing in: {{ name }}

But it gives me the same ID number for each item or instance the module creates.

Is there a way to have it produce completely different IDs for each item within the module?

Hey @kchung would you mind sending over a screenshot of your code? Are you trying to have a unique id/class usign {{ name }} for each module instance (e.g. an image module is added to a page three times) or for a module field in a for loop (e.g. a tabber with repeatable tabs)?

Jason,

Its on line 4.

I tried placing it in Class and then I tried it with id=“” - as you see it in the screen capture.

Hey @kchung thanks for sending that example! So {{ name }} would be individual to the module as a whole and not a field within a repeater of the module. For example if you added {{ name }} to the top level class on your module (on line 1), each time you added that module to a page the module you added would have a unique class name. If you wanted to have a unique class name for each item in a loop I’d recommend {{ loop.index }} (For Loops - HubSpot docs). For example:

{% for item in forloop %}

<div id=“story-item-{{ loop.index }}”>

</div>

{% endif %}

This should output a number after “story-item-” for the ID which should keep each loop item unique.

Hi Jason,

That works! It created a unique ID for each of the items within the module. Now I can target each item to re-style in CSS.

Thank you so much!

No problem! Happy to hear it worked