No way to output hubL variables in JavaScript file?

SOLVE
BenDTU
Member

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 Accepted solution

Accepted Solutions
dennisedson
Solution
Community Manager

@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

Thanks,

Dennis


We are excited to announce that the Community will be launching a weekly newsletter on November 2, 2020!
Sign up today!

View solution in original post

0 Upvotes
4 Replies 4
dennisedson
Solution
Community Manager

@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

Thanks,

Dennis


We are excited to announce that the Community will be launching a weekly newsletter on November 2, 2020!
Sign up today!

View solution in original post

0 Upvotes
BenDTU
Member

That makes sense, thanks again.

0 Upvotes
derekcavaliero
Top Contributor | Diamond Partner

@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.

JTenbrink
Member

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;