I provision custom page layout through elements.xml

I want to add a javascript file to that page to be used by some webparts put on that page through elements.xml as well.

In my custom page layout i add

<asp:ContentPlaceHolder id="PlaceHolderAdditionalPageHead" runat="server">
<script src="/SiteAssets/SomeScript.js"></script>

which works fine. But i want this code to be site url independent, meaning this needs to work on any site collection either with managed path or not. How can i inject ~site token into script tag?


3 Answers 3


In Sandbox, you can resolve the tokens using Literals:

<asp:ContentPlaceHolder id="PlaceHolderAdditionalPageHead" runat="server">

<asp:literal ID="Literal1" runat="server" Text="&lt;script src='" />
<asp:literal ID="Literal2" runat="server" Text="<% $SPUrl:~site/SiteAssets/SomeScript.js %>" />
<asp:literal ID="Literal3" runat="server" Text="' type='text/javascript' &gt;&lt;/script&gt;" />

  • If I'm not wrong it does not work in sharepoint foundation.
    – Alexander
    Aug 19, 2012 at 16:25
  • I doubt the tokens will work on foundation since they are part of the publishing dll which is not present in foundation. Aug 19, 2012 at 16:47
  • This does gets job done. But i tried to combine 3 literal into one one, but didn't succeed. It's a bummer, if i have 3 scripts, i need to add 9 lines. Thank you.
    – dotsa
    Aug 19, 2012 at 18:21
  • That is sandbox for you :) Aug 19, 2012 at 18:41

Have you tried something like this?

<asp:ContentPlaceHolder id="PlaceHolderAdditionalPageHead" runat="server">
<script src="<%= SPContext.Current.Web.ServerRelativUrl.TrimEnd('/') %>/SiteAssets/SomeScript.js"></script>
  • Parser Error Message: Code blocks are not allowed in this file <asp:Content ContentPlaceHolderId="PlaceHolderAdditionalPageHead" runat="server"> <script runat="server" src="<%= SPContext.Current.Web.ServerRelativUrl.TrimEnd('/') %>/SiteAssets/SomeScript.js"></script> </asp:Content>
    – dotsa
    Aug 19, 2012 at 18:07

You can use ScriptManagerProxy, considering your MasterPage already has a ScriptManager (what is true even for OOB Master Page).

With it you can use 'SPUrl` and its tokens.

In you page layout just add:

<asp:ScriptManagerProxy runat="server">
        <asp:ScriptReference Path="<% $SPUrl:~sitecollection/Style Library/my_js_file_path.js %>" />

But do not add this snipper in the PlaceHolderAdditionalPageHead, you will get exceptions there. Add it to the PlaceHolderMain. Do not worry your scripts files will still be inserted at your page's head.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.