21277 Posts in 5728 Topics by 2599 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, Howard, Sean, Ryan M., biapar, Willr, Ingo, swaiba, simon_w
| Go to End | ||
| Author | Topic: | 2764 Views |
-
Re: passing silverstripe variables into inline javascript [SOLVED]

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.
| 2764 Views | ||
| Go to Top |

