XF 2.2 How to correctly read XF variable with Javascript


I need to run a code according to the screen size.

So I've put the JS inside XF var and if I "alert" or "console.log" I can see the variable, but when calling the variable in XF it returns nothing.

How to correctly read the XF variable in this case?

<xf:set var="$screen"><xf:js>window.innerWidth;</xf:js></xf:set>
<xf:if is="{$screen} > 650">
     ...... code .......
It doesn't work like that, a PHP variable is defined server side and a javascript variable is defined client side. You can't set a PHP variable with javascript.

To do what you want there you'd either want CSS media queries to hide and show a div based on screen size, or write javascript to do whatever you're trying to do.
Well, I did a workaround to get the value, almost there.

I got the javascript value into xf variable, it can be read and printed as below:

<xf:set var="$screen"><script>document.write(window.innerWidth);</script></xf:set>

<xf:if is="{{$screen}}">screen: {{$screen}}</xf:if>

But when I do comparison it doesn't work, it seems to be a string and the conversion to number is not working:

<xf:set var="$screen"><script>document.write(window.innerWidth);</script></xf:set>

<xf:if is="{{$screen|number}} < 650">screen: {{$screen}}<xf:else />bigger</xf:if>

Template public:PAGE_CONTAINER: [E_WARNING] Object of class XF\PreEscaped could not be converted to float (src/XF/Language.php:855)

How can I do the conversion to number in order to have the comparison?
Again, that’s not doing what you think it is. The $screen variable is populated with javascript that then gets rendered on the page and outputs the value in your browser because your browser executes the javascript. But the $screen variable does not contain the actual value. It is physically impossible to set a PHP variable with javascript.
Put this in your template:

<xf:set var="$screen"><script>document.write(window.innerWidth);</script></xf:set>

It will output this:


The value of $screen is literally <script>document.write(window.innerWidth);</script>, so if you dump it out it displays a number in your browser because your browser runs the javascript, but it's not assigned in PHP. PHP is a server side language and the templates are compiled to PHP, you cannot set a value from javascript.
Top Bottom