Pass SS variable to JS

Silverstripe Version: 4.3.3

Hey,
I’m trying to pass a ss variable to an external js file, so I can call it in a function.
I read the tutorial and tried the following:

In my KontaktPageController which extends PageController:

public function init()
    {
        parent::init();
        Requirements::javascriptTemplate($this->ThemeDir().'/javascript/google-maps.js', array(
            "ThemeDir" => $this->ThemeDir()
        ));
    }

Regarding the tutorial I should be able to call $ThemeDir inside the google-maps.js.

But the only thing I’m getting is:

[2019-11-06 15:36:32] error-log.ERROR: Uncaught Exception InvalidArgumentException: "Javascript template file /html/resources/themes/fhd-simple/javascript/google-maps.js does not exist" at /var/www/html/vendor/silverstripe/framework/src/View/Requirements_Backend.php line 609 {"exception":"[object] (InvalidArgumentException(code: 0): Javascript template file /html/resources/themes/fhd-simple/javascript/google-maps.js does not exist at /var/www/html/vendor/silverstripe/framework/src/View/Requirements_Backend.php:609)"} []

If I use Requirements::javascript instead of Requirements::javascriptTemplate the .js file is loading, but $ThemeDir is undefined, so I have no access to the variable. I don’t understand why the file does not exist, cause I see it exists when I use just ::javacript

Any ideas how I can get it to work?

You’ll probably need to use the resource loader to find the JS:

 $script = ThemeResourceLoader::inst()->findThemedJavascript('google-maps.js');
 Requirements::javascriptTemplate($script, ['ThemeDir' => $this->ThemeDir()]);

As an aside, the ThemeDir() method is deprecated. If you look at it in the code, you can see which functions will replace it.

1 Like

Thanks a lot, its working with your code!

1 Like