Jump to:

23480 Posts in 18951 Topics by 2878 members

General Questions

SilverStripe Forums » General Questions » passing silverstripe variables into inline javascript [SOLVED]

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

Page: 1 2
Go to End
Author Topic: 4151 Views
  • timwjohn
    Community Member
    98 Posts

    Re: passing silverstripe variables into inline javascript [SOLVED] Link to this post

    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.

Page: 1 2
Go to Top

Want to know more about the company that brought you SilverStripe? Then check out SilverStripe.com

Comments on this website? Please give feedback.