XF 2.2 How to correctly read XF variable with Javascript

FoxSecrets

Active member
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?


Code:
<xf:set var="$screen"><xf:js>window.innerWidth;</xf:js></xf:set>
<xf:if is="{$screen} > 650">
     ...... code .......
</xf:if>
 
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:

Code:
<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:

Code:
<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>

Code:
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:

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

It will output this:

1689461059668.png

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