Jump to:

23355 Posts in 17734 Topics by 2862 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: 4022 Views
  • timwjohn
    Avatar
    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():

    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.

    4022 Views
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.