EE Conditionals in JavaScript

I’ve run into this problem more than once, and I’m adding this to the list of ExpressionEngine tips. By writing it down, hopefully I’ll remember it on future projects. EE conditionals do not work in JavaScript by default. For example, building an array of images using the following code will not work:

<script>
var imageArray = new Array (

{exp:channel:entries channel="listings" disable="member_data|pagination" category="3"
limit="1"}
'<img src="{listings_img_1}" width="300" height="253">'{if listings_img_2 != ''},
'<img src="{listings_img_2}" width="300" height="253">'{if:elseif listings_img_3 != ''},
'<img src="{listings_img_3}" width="300" height="253">'{if:elseif listings_img_4 != ''},
'<img src="{listings_img_4}" width="300" height="253">'{if:elseif listings_img_5 != ''},
'<img src="{listings_img_5}" width="300" height="253">'{/if}
{/exp:channel:entries}

);
</script>

The conditional tags will not get parsed. However, by adding a line to the /system/expressionengine/config/config.php file, EE conditionals will work in JavaScript. Add the following line to your config.php file:

$config['protect_javascript'] = 'n';

Reference: http://expressionengine.com/forums/viewthread/221319/

Leave a Reply

Your email address will not be published. Required fields are marked *