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.

We've moved the forum!

Please use forum.silverstripe.org for any new questions (announcement).
The forum archive will stick around, but will be read only.

You can also use our Slack channel or StackOverflow to ask for help.
Check out our community overview for more options to contribute.

Template Questions /

Moderators: martimiz, Sean, Ed, biapar, Willr, Ingo, swaiba

JavaScript in the Template


Go to End


2 Posts   5374 Views

Avatar
squarefighter

Community Member, 1 Post

2 April 2013 at 10:56am

I've looked up a couple ways to do this, but none work quite how I would like them to. I want to require JavaScript using the template, rather than the controller, so that I can put it in specific places. I'll have modernizr at the top and jquery + custom scripts at the bottom of the page. According to the documentation at http://doc.silverstripe.org/framework/en/reference/requirements, I should be able to do that with:

<% require javascript(cms/javascript/LeftAndMain.js) %>

It can't seem to find it, I've tried several variations on that with different paths. The page loads, but where the script tag should be is just blank. I was able to get the scripts to load with:

Requirements::javascript("themes/tcc/js/modernizr-2.6.2.min.js");

But that doesn't allow me to set the position. It also doesn't lend itself well to theme development, since it's outside of the template directory. I can also get it to work with a standard script tag:

<script src="/themes/tcc/js/jquery-1.9.1.min.js"></script>

But that doesn't really take advantage of the SilverStripe templating engine. Any suggestions?

Avatar
Optic Blaze

Community Member, 190 Posts

7 April 2013 at 9:51am

Hello

1) If you want to require jquery.javascript files You could try ....
<script type="text/javascript" src="{$ThemeDir}/tcc/js/jquery-1.9.1.min.js"></script>

$ThemeDir can be set i your config.php file or in the CMS -> Settings section

2) If you need to include specific scripts eg <script> alert('Hello') </script> you could put it in a seperate .ss file and then just load it with the <% include MyScript.ss %> command

3) Just remember that if you use require to load in javascript it tends to load it at the bottom of the page. That is because it is more efficient to load jquery and javascript files at the end of the page.

Hope it help