Technique described below can be actually used for regular ASP.Net applications when you need to pass some server variable into javascript code – i.e. in general it is not Sharepoint-specific. Nevertheless I used it recently to pass locale of current SPWeb into external .js file.
We often use server variables in javascript code when we need to determine ClientID of some server control in javascript code embedded into page:
1: var txtEmail = document.getElementById("<%= this.txtEmail.ClientID %>")
Unfortunately this approach can’t be used when javascript code is located in external .js file (btw this is recommended approach for web applications development – do not mess layout and javascript code) because .js file is not processed by ASP.Net by default.
The main idea for external .js file is quite simple – use global variable (of course you can use namespaces as well, but in this post I will use global variable for simplicity) which will be available in .js file and which will keep locale of current SPWeb:
1: <%@ Import Namespace="Microsoft.SharePoint" %>
2: <script type="text/javascript">
3: var globalLocale = "<%= SPContext.Current.Web.Language %>";
4: </script>
To use this variable in .js file the following function was added:
1:
2: getLocaleOfCurrentSiteOrEmpty = function() {
3: var localLocale = "";
4: try {
5: localLocale = globalLocale;
6: }
7: catch (e) {
8: localLocale = "";
9: }
10: return localLocale;
11: }
So those pages which don’t have globalLocale defined will have empty value and then use some default settings.
Keeping in mind DRY principle we didn’t want to copy and past definition of globalLocale variable in each page where it is required. In order to avoid duplication several approaches can be used:
We used 2nd approach – but if you are not able to use user controls because of some reasons, 1st way is applicable as well.