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
Reply


9 Posts   4488 Views

Avatar
timwjohn

Community Member, 98 Posts

5 November 2010 at 4:44am

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

PHP:

class Home_Controller extends Page_Controller
{
   function init()
   {
      parent::init();
      Requirements::javascript('mootools-core-1.3-full-nocompat.js');
      Requirements::javascript('slideshow.js');
      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 = [
   {
      imageURL:"/site/assets/Uploads/D5120018.JPG",
      thumbURL:"/site/assets/Uploads/_resampled/croppedimage5050-D5120018.JPG"
   },
   {
      imageURL:"/site/assets/Uploads/D250007.JPG",
      thumbURL:"/site/assets/Uploads/_resampled/croppedimage5050-D250007.JPG"
   },
   {
      imageURL:"/site/assets/Uploads/DMG3025.JPG",
      thumbURL:"/site/assets/Uploads/_resampled/croppedimage5050-DMG3025.JPG"
   }
]

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

eval('$slidesString');

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