Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

General Questions /

General questions about getting started with SilverStripe that don't fit in any of the categories above.

Moderators: martimiz, Sean, biapar, Willr, Ingo, swaiba, simon_w

passing silverstripe variables into inline javascript [SOLVED]

Go to End

9 Posts   4488 Views


Community Member, 98 Posts

5 November 2010 at 4:44am

This is how I ended up doing it in the end, using Requirements::javascriptTemplate():


class Home_Controller extends Page_Controller
   function init()
      Requirements::javascriptTemplate('home.js', array(
         "slidesString" => $this->getSlidesString()
   function getSlidesString()
      $slides_string = "slides = [";
      $slideshow_images = $this->SlideshowImages();
      $num_items = count($slideshow_images);
      $i = 1;
      foreach ($slideshow_images as $slideshow_image)
         $imageURL = $slideshow_image->Image()->URL;
         $thumbURL = $slideshow_image->Image()->CroppedImage(50, 50)->URL;
         $slides_string .= "{imageURL:\"$imageURL\",   thumbURL:\"$thumbURL\"}";
         if ($i ++ < $num_items)
            $slides_string .= ",";
      $slides_string .= "]";
      return $slides_string;

This will replace the $slidesString pseudovariable in script.js with the following as a string (without the nice indentation):

slides = [

In script.js, I use the eval() function to execute this code, creating and populating the variable 'slides':


window.addEvent('domready', function()
   new Slideshow({slides: slides, shuffle: true});

I prefer this method as only the variable is generated in PHP, rather than the whole script, which is maintained in its own separate js file.

Go to Top