How to Apply a Custom Web Template Using JSOM (Javascript SharePoint Object Model)


When you’re creating a SPWeb from JSOM and want to apply a webtemplate, you would probably want to use the method Web.ApplyWebTemplate. Unfortunately this method is not really helpful in the Javascript Object Model because the provisioning of the SPWeb allready applies a template (by default) and applying a template is not applicable anymore. Even if you leave the WebTemplate empty or null in the WebCreationInformation object.

The good news is the solution is really simple. To apply your custom webtemplate you can just use the {FEATUREID}#WebTemplateName in the WebCreationInformation Object.

function onQuerySucceeded(sender, args) {
  alert('Title: ' + this.oNewWebsite.get_title() + ' Decription: ' + this.oNewWebsite.get_description());
}

function onQueryFailed(sender, args) {
  alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
}

function createWebSite() {
  var webDescription = 'A new site from custom web template';
  var webLanguage = 1043;
  var webTitle = 'Test Web Site';
  var webUrl = 'testwebsite';
  var webPermissions = false;
  // Just insert your reference to your feature and webtemplate here
  var webTemplate = '{4a110786-9683-4734-97ca-f2eca95ca377}#WTProject';
  var siteUrl = '/sites/pr01';
  var clientContext = new SP.ClientContext(siteUrl);
  this.oWebsite = clientContext.get_web();
  var webCreateInfo = new SP.WebCreationInformation();
  webCreateInfo.set_description(webDescription);
  webCreateInfo.set_language(webLanguage);
  webCreateInfo.set_title(webTitle);
  webCreateInfo.set_url(webUrl);
  webCreateInfo.set_useSamePermissionsAsParentSite(webPermissions);
  webCreateInfo.set_webTemplate(webTemplate);
  this.oNewWebsite = this.oWebsite.get_webs().add(webCreateInfo);
  // This is not working, because a webtemplate is applied by default.
  // this.oNewWebsite.applyWebTemplate("{4a110786-9683-4734-97ca-f2eca95ca377}#WTProject");
  clientContext.load(this.oNewWebsite);
  clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}
SP.SOD.executeFunc('core.js', 'SP.ClientContext', createWebSite);
Advertisements