Skip to main content

Microsoft

Sitecore Powershell – Add rendering to item

The Sitecore Powershell Module has once again come to the rescue to save me a lot of time in a recent update.
We made an update to a left navigation component for mobile views in our responsive site. That being said the component needed to be added to a hundred+ product pages so that the navigation and an additional social media component displayed in mobile view.
I came up with a powershell script based off of other scripts that I’ve had to work with and thought I would share, just in case someone needed to do the same thing.

$root = gi master:// -id "{076927BD-FFD2-4658-B522-D836C045CF7D}"
$items = $root | ls -r | ?{$_.TemplateName -eq "ProductPage"}
$leftNavRendering = gi master:\layout\Renderings\Site\Components\LeftNav | New-Rendering -Placeholder "contentMain"
$socialMediaRendering = gi master:\layout\Renderings\Site\Components\SocialMedia\SocialMediaBar | New-Rendering -Placeholder "contentMain"
foreach($i in $items){
    if($leftNavDsPath){
        clear-variable("leftNavDsPath")
    }
    if($leftNavDs){
        clear-variable("leftNavDs")
    }
    if($sMPath){
        clear-variable("sMPath")
    }
    if($sMDs){
        clear-variable("sMDs")
    }
    $leftNavDsPath = [string]::Format("master:/{0}/Local Assets/Left Nav", $i.Paths.Path)
    $leftNavDs = gi -Path $leftNavDsPath
    $sMPath = [string]::Format("master:{0}/Local Assets/LeftNavSocialMedia", $i.Paths.Path)
    $sMDs = gi -Path $sMPath
    Add-Rendering -Item $i -Rendering $socialMediaRendering -Placeholder "contentMain" -Parameter @{"HideInDesktop"=1; } -Datasource $sMDs.Paths.Path
    Add-Rendering -Item $i -Rendering $leftNavRendering -Placeholder "contentMain" -Parameter @{"HideInDesktop"=1; } -Datasource $leftNavDs.Paths.Path
}

This script is started from a parent page that has pages of type “ProductPage” as children.
I pulled the left navigation and social media components from the renderings folder and created the new rendering that will be added to each page.
Inside the foreach loop paths and datasource for each component are pulled from the page’s /Local Assets folder. The /Local Assets folder is where we’ve put all page-specific content.
Once the datasources are retrieved I simply use the Add-Rendering cmdlet. In researching the Add-Rendering parameters most blogs and documentation pointed out to use ‘-Parameter @{FieldName=”HideInDesktop”;Value=$true;}. While the rendering was being added correctly, the rendering parameters was not getting set. After some trial and error using ‘-Parameter @{“HideInDesktop”=1;}.
 
If you have any comments or suggestions please feel free to add them here or on Twitter @bill_cacy.
Thanks!
 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

William Cacy

More from this Author

Categories
Follow Us
TwitterLinkedinFacebookYoutubeInstagram