Jump to:

3447 Posts in 1032 Topics by 872 members

Template Questions

SilverStripe Forums » Template Questions » JavaScript in the Template

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

Page: 1
Go to End
Author Topic: 971 Views
  • squarefighter
    Community Member
    1 Post

    JavaScript in the Template Link to this post

    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:


    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?

  • Optic Blaze
    Community Member
    162 Posts

    Re: JavaScript in the Template Link to this post


    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

Page: 1
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.