I am trying to do some JavaScript with Smarty and using JavaScript variable and checking if the value is contained within a Smarty array.
Below is the code that I have:
if (object.data[i].Application === selectedApplication || {if isset($Applications) && $Applications|@count > 0} true {else} false {/if})
{
{if not isset($Applications)}
$("#cboApplications").append("<option selected value=\""+object.data[i].id+"\">"+object.data[i].Application+"</option>");
{else}
{if '9'|in_array:$Applications}
console.log("id " + id + " in array");
$("#cboApplications").append("<option selected value=\""+object.data[i].id+"\">"+object.data[i].Application+"</option>");
{else}
console.log("id " + id + " not in array");
$("#cboApplications").append("<option value=\""+object.data[i].id+"\">"+object.data[i].Application+"</option>");
{/if}
{/if}
}
The issue I am having with is {if '9'|in_array:$Applications}
. At the moment I've hard-coded the value instead of using the JavaScript variable as a test but I get the same results.
Below is what the array looks like when printed from inside Smarty:
array (
0 => '9',
)
There are multiple values in this list box cboApplications
which have a value of 8, 5, 6, 9 and 10.
For some reason, even though only 9 is in the $Applications array, the console.log is acting as if every single item is inside the array, not just 9.
You have to use {literal}
in Smarty for JavaScript. Example:
{literal}
<script type="text/javascript">
document.write("{/literal}{$text}{literal}");
</script>
{/literal}
For more information, see Smarty Documentation.
Can you maybe try something like this:
if (object.data[i].Application === selectedApplication || {if isset($Applications) && $Applications|@count > 0} true {else} false {/if})
{
{if not isset($Applications)}
$("#cboApplications").append("<option selected value=\""+object.data[i].id+"\">"+object.data[i].Application+"</option>");
{else}
{if $Applications.indexOf('9') != -1}
console.log("id " + id + " in array");
$("#cboApplications").append("<option selected value=\""+object.data[i].id+"\">"+object.data[i].Application+"</option>");
{else}
console.log("id " + id + " not in array");
$("#cboApplications").append("<option value=\""+object.data[i].id+"\">"+object.data[i].Application+"</option>");
{/if}
{/if}
}
I replaced inArray with javascript indexOf, so maybe that can help.
You are always checking if 9 is in the $Applications
array, so it always passes because we know that 9 is in the array.
Can you provide the actual code which is checking the variable instead 9? Also keep in mind that the smarty code is executed on the server while the JavaScript does not so I can't really imagine what are you trying to achieve. Actual code might help.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With