Writing dynamic tag in master page head element
-
19-01-2021 - |
Question
I want to add the <base>
element(https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base) in my masterpage <head>
. I want it to be dynamic so whe the masterpage is used on different sub/sites it writes the correct href. For example it might resolve to the following when reused...
I think I need to use the ~site
token, but I'm not sure how I mark it up to tell SharePoint to expand the token in a base tag. In the past I've used SharePoint:ScriptLink and SharePoint:CssRegistration to dynamically add things to the page. But I'm not sure what model to follow here?
What control/markup do I need to add to my .html masterpage to get it to correctly render <base href="current site url" />
?
EDIT
Found this answer which is close. I tried the following values:
<base href="<%$SPUrl:~site%>" runat="server" />
<base href="$SPUrl:~site" runat="server" />
<base href="~site" runat="server" />
The first one throws an error that < is an illegal character. The rest just append ~site to the end of the tag. What I'm missing is the part that SP uses from the masterpage html that tells the asp to expand the token and then rewrite it as an actual tag...
Solution
If you use the .html master page, this should render the base tag:
<!--SPM:<asp:Literal runat="server" Text="<base href='"/>-->
<!--SPM:<asp:Literal runat="server" Text="<% $SPUrl:~site/ %>"/>-->
<!--SPM:<asp:Literal runat="server" Text="'/>"/>-->
And if you are editing the .master page, than this should do it:
<base href='<asp:Literal runat="server" Text="<% $SPUrl:~site/ %>"/>' />
You can also use the $SPUrl:~sitecollection
if you need the absolute path.