Search code examples
javascriptruby-on-railsslim-lang

rails slim template: Uncaught SyntaxError: Unexpected token if


I've a slim template previews.slim

= render 'previews/demo_areas/skinny_demo_area', p_unit: @p_unit, size: 2

I added javascript on that file:

javascript:
  var rotationIndex = 0;
  var auto_rotate = #{@p_unit.auto_rotate_highlight};
  - if auto_rotate
    rotateTextOverAds();

  function rotateTextOverAds() {
    var size_300x250_ads = $('.carousel_ad_unit.size_9700x250 .ad .ad-details');
    $('.carousel_ad_unit.size_9700x250 .ad').each(function () {
      $(this).find('.ad-details').hide();
    });

    rotationIndex += 1;
    if rotationIndex > size_300x250_ads.length
      rotationIndex = 1;
    size_300x250_ads[rotationIndex - 1].style.display = 'block';

    setTimeout(rotateTextOverAds, 2000)
  }

Based on a rails instance variable @p_unit.auto_rotate_highlight attribute, I would like to run a function. But when I load the page, my browser keep showing:

Uncaught SyntaxError: Unexpected token if

How can I resolve this?


Solution

  • You're mixing javascript syntax and ruby(slim) syntax, in the javascript if conditional looks like:

    if (condition) {
      // some code here
    }