簡體   English   中英

如何使用 PnP JS 在 SharePoint 中以編程方式添加頁面/Web 部件區域/Web 部件?

[英]How to add pages / web-part zones / web-parts programmatically in SharePoint online using PnP JS?

我創建了頁面,然后使用下面的 function 以編程方式添加了 Web 部件區域/Web 部件,

function addWebPart(webUrl, pageUrl,webPartXml,zoneId,zoneIndex, Success,Error){
var context = new SP.ClientContext(webUrl);
var web = context.get_web();

var file = web.getFileByServerRelativeUrl(webUrl + pageUrl);
var webPartMngr = file.getLimitedWebPartManager(SP.WebParts.PersonalizationScope.shared);
var webPartDef = webPartMngr.importWebPart(webPartXml);
var webPart = webPartDef.get_webPart();
webPartMngr.addWebPart(webPart, zoneId, zoneIndex);

context.load(webPart);
context.executeQueryAsync(
  function() {
    Success(webPart);
  },
  Error
);

現在,我需要創建一個頁面,然后使用 PnP JS 以編程方式在 SharePoint 中在線添加 Web 部件區域/Web 部件。

任何人都可以幫助我嗎?

提前致謝。

你可以參考這個問題: https://github.com/pnp/pnpjs/issues/557

使用 PnPJS,您需要在頁面中抓取 webpart xml 並將其添加到頁面內容中。

import { sp } from "@pnp/sp";
const mynewpageContent =
`<%@ Page Inherits="Microsoft.SharePoint.Publishing.TemplateRedirectionPage,Microsoft.SharePoint.Publishing,Version=16.0.0.0,Culture=neutral,PublicKeyToken=71e9bce111e9429c" %> <%@ Reference VirtualPath="~TemplatePageUrl" %> <%@ Reference VirtualPath="~masterurl/custom.master" %>
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<html xmlns:mso="urn:schemas-microsoft-com:office:office" xmlns:msdt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882"><head>
<!--[if gte mso 9]><SharePoint:CTFieldRefs runat=server Prefix="mso:" FieldList="FileLeafRef,Comments,PublishingStartDate,PublishingExpirationDate,PublishingContactEmail,PublishingContactName,PublishingContactPicture,PublishingPageLayout,PublishingVariationGroupID,PublishingVariationRelationshipLinkFieldID,PublishingRollupImage,Audience,PublishingIsFurlPage,PublishingPageImage,PublishingPageContent,SummaryLinks,SummaryLinks2,SeoBrowserTitle,SeoMetaDescription,SeoKeywords,RobotsNoIndex"><xml>
<mso:CustomDocumentProperties>
<mso:PublishingPageContent msdt:dt="string"></mso:PublishingPageContent>
<mso:ContentType msdt:dt="string">Welcome Page</mso:ContentType>
<mso:PublishingPageLayout msdt:dt="string">https://contoso.sharepoint.com/sites/site/_catalogs/masterpage/ArticleLeft.aspx, Article Left</mso:PublishingPageLayout>
</mso:CustomDocumentProperties>
</xml></SharePoint:CTFieldRefs><![endif]-->
<title>Home</title></head>`;

(async () => {
    
    const page = await sp.web.getFolderByServerRelativeUrl('/sites/site/pages').files.add('mynewpage.aspx', mynewpageContent, true)
    console.log('Done');

})()
    .catch(console.warn);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM