0

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>
</asp:ContentPlaceHolder>

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?

1

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;" />

</asp:ContentPlaceHolder>
  • If I'm not wrong it does not work in sharepoint foundation. – Alexander Aug 19 '12 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. – Vardhaman Deshpande Aug 19 '12 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 '12 at 18:21
  • That is sandbox for you :) – Vardhaman Deshpande Aug 19 '12 at 18:41
0

Have you tried something like this?

<asp:ContentPlaceHolder id="PlaceHolderAdditionalPageHead" runat="server">
<script src="<%= SPContext.Current.Web.ServerRelativUrl.TrimEnd('/') %>/SiteAssets/SomeScript.js"></script>
</asp:ContentPlaceHolder>
  • 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 '12 at 18:07
0

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">
    <Scripts>
        <asp:ScriptReference Path="<% $SPUrl:~sitecollection/Style Library/my_js_file_path.js %>" />
    </Scripts>
</asp:ScriptManagerProxy>

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, privacy policy and cookie policy

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