XF 2.1 How to check a variable using a conditional? (XF Template)

Arnox

Active member
I can't believe this has never been asked before, but anyway, here is my code so far.

HTML:
<xf:set var="$number">
    {{ rand(1,3) }}
</xf:set>
<xf:if is="{$number} == 1">
    <a href="URL"><img src="image URL"></a>
<xf:else />
    <p>{$number}</p>
</xf:if>

The problem here is specifically this line:
Code:
<xf:if is="{$number} == 1">

If it is as above, it will always fire and display the image, no matter what the random number is. But if it is as below:
Code:
<xf:if is="{$number} == '1'">

It will never fire and will just print out the variable.

What it SHOULD be doing is firing if the random number is 1 and just printing the variable otherwise. I've looked all over and I'm not sure what the hell the issue is here.
 
Change the first 3 lines to:

HTML:
<xf:set var="$number" value="{{ rand(1,3) }}" />
Just as you posted this, I figured it out. XD But thank you so much anyway! It's incredibly weird that that was the issue the entire time.

Also, for reference, I found out you can also get a random integer by doing {{ {$xf.time} % x + 1 }} instead of {{ rand(1,x) }}, where x is the maximum random integer you want. Not sure how useful that's going to be for anyone, but it's there.
 
It's incredibly weird that that was the issue the entire time.
Your first statement includes the whitespace into the value, so your first check attempts to match a string to an integer, and because you chose loose matching (two instead of three equal-signs) it attempts a best case boolean match, where true equals true is always true. Your second check then is a clear string vs string match, but " 1 " is not equal to "1", so it'll always be false.

You could've probably gotten away with
HTML:
<xf:set var="$number">{{ rand(1,3) }}</xf:set>
or
HTML:
<xf:set var="$number"><xf:trim>
{{ rand(1,3) }}
</xf:trim></xf:set>

but this is definitely the cleanest.
HTML:
<xf:set var="$number" value="{{ rand(1,3) }}" />
 
Back
Top Bottom