CMS Development

BenDTU
Membre

No way to output hubL variables in JavaScript file?

Résolue

I'm trying to access {{ group.absolute_url }} within a Javascript file, but I'm unable to get any of the 'standard' variables to output anything. No matter which variable I try it comes up an empty string.

 

Is this unsupported within pure JS files? I'm needing it for some JS trickery around the tag filter, which doesn't seem to have its own section to execute JavaScript within as it's a standard module (Or so I assume). Is there another approach I can take here that would work?

1 Solution acceptée
dennisedson
Solution
Équipe de développement de HubSpot
Équipe de développement de HubSpot

No way to output hubL variables in JavaScript file?

Résolue

@BenDTU , you cannot add hubl code to a js file.

if you need it, you could make a hidden span with the  {{  }} and then set it as a variable in js

or set an element attribute to it and find it.  whatever is more appropriate for your scenario

Voir la solution dans l'envoi d'origine

0 Votes
4 Réponses
JTenbrink
Membre | Partenaire solutions Diamond
Membre | Partenaire solutions Diamond

No way to output hubL variables in JavaScript file?

Résolue

You can pass data to js through dataset though. Find a html element that you can target via javascript querySelector and attach the data to it.  See below. 

 

<div id="group-container" data-url="{{ module.absolute_url }}">
</div>

 

Then in your javascript target the html element with querySelector. 

const container = document.querySelector('#group-container');

 

Then get the url via the .dataset attribute on the element. 

const url = container.dataset.url;

 

dennisedson
Solution
Équipe de développement de HubSpot
Équipe de développement de HubSpot

No way to output hubL variables in JavaScript file?

Résolue

@BenDTU , you cannot add hubl code to a js file.

if you need it, you could make a hidden span with the  {{  }} and then set it as a variable in js

or set an element attribute to it and find it.  whatever is more appropriate for your scenario

0 Votes
BenDTU
Membre

No way to output hubL variables in JavaScript file?

Résolue

That makes sense, thanks again.

0 Votes
derekcavaliero
Contributeur de premier rang | Partenaire solutions Diamond
Contributeur de premier rang | Partenaire solutions Diamond

No way to output hubL variables in JavaScript file?

Résolue

@BenDTU 

 

Another thing I have done to make this work is to set a localized global object where I can expose certain HUBL data for access inside modules.

 

Generally speaking, you wouldn't want to do too much of this, but its really helpful for common variables you might need access to in different contexts. I recommend doing this in the content settings <head> output.

Derek Cavaliero
Director of Engineering

WebMechanix
www.webmechanix.com