Ramakant Chandel, Author at Perficient Blogs https://blogs.perficient.com/author/rchandel/ Expert Digital Insights Tue, 04 Aug 2020 15:29:43 +0000 en-US hourly 1 https://blogs.perficient.com/files/favicon-194x194-1-150x150.png Ramakant Chandel, Author at Perficient Blogs https://blogs.perficient.com/author/rchandel/ 32 32 30508587 SXA Scriban: Creating Custom Embedded Function in Scriban https://blogs.perficient.com/2020/08/03/sxa-scriban-creating-custom-embedded-function-in-scriban/ https://blogs.perficient.com/2020/08/03/sxa-scriban-creating-custom-embedded-function-in-scriban/#respond Mon, 03 Aug 2020 15:52:46 +0000 https://blogs.perficient.com/?p=278212

With the release of Sitecore SXA 9.3.0, it came with Scriban Templates. They are used in Rendering Variants and can provide many benefits to the Content Authors as well as Developers. With additions like Scriban, Content Authors will have more power over the presentation of Content in Sitecore.

There are already many embedded functions provided inbuilt by Scriban in SXA 9.3.0. Let’s have a look at the list of these functions:

scriban template functions

You can see that these can be used in a wide range of scenarios making it easy to access and show information that often requires writing backend code.

But, we only have these functions, any information that they cannot provide need to be accessed using Custom Embedded methods that we can write in our solution. Let’s create a custom embedded function which will return Sitecore App Setting value.

Requirement

To create a Custom Embedded function, it will take the App Setting name string and return the value associated with that Setting.

Solution

To add a Custom Embedded Function, we need to add a Pipeline Processor to the generateScribanContext Pipeline. This is the processor where we will write our function logic.

Create a code file to write the Processor:

Create a new class file named CustomEmbeddedMethods.cs inside Pipelines folder and include following namespaces:

usingRuntime;
usingXA.Foundation.Abstractions;
usingXA.Foundation.Scriban.Pipelines.GenerateScribanContext;

You can use NuGet Package manager to get these.

Next, have our newly created class implement IGenerateScribanContextProcessor interface. Add a Process method to make it look like below image:

 

Scribancustomfunc2

Next, add a function to our class with the following code:

Scribancustomfunc3

 

This is the function where we will fetch the Sitecore App Setting using settingName parameter.

Import Method of GlobalScriptObject

Now, the next part is adding/importing our function definition to the Scriban Script object and associating it with our Scriban Function name. For this, we will need to create a Delegate for our function.

Delegates – Delegates are a reference type of variables that hold the reference to a method. They are useful as a reference can be changed at runtime. This is just like Function Pointers in C/C++. The importance of a delegate is that we have flexibility. A delegate can be assigned any method that has the same signature and it will be called each time associated Delegate is called.

Now, we need this as the Import function that we are using has below signature:

public static void Import(this IScriptObject script, string member, Delegate function);

 

Now, let’s add a delegate declaration for GetSettings method (name simplified for understanding):

 

private delegate string delegateGetSetting(string settingName);

 

Now, the code should look like this:

Scribancustomfunc4

Next, we will instantiate Delegate by passing the name of our method:

 

var getSetting = new delegateGetSetting(GetSettings);

We have Function definition ready and Delegate is ready. So, it is time to associate GetSetting function with an Embedded function that we can use in Scriban Temlate item.

 

args.GlobalScriptObject.Import("sc_get_settings", getSetting);

 

sc_get_settings is the name of embedded function that we are going to use in Scriban Template item.

The code part is done now. Your class should look like this:

Scribancustomfunc5

 

Config Patch for Pipeline

Create a Config Patch file for adding Pipeline Processor to generateScribanContext Pipeline:

Scribancustomfunc6

 

Config Patch for Sitecore App Settings

Create a Config Patch file where we will add Sitecore App Settings to test our Embedded function:

Scribancustomfunc7

 

TESTING

We can use {{ sc_get_settings }} in Scriban template item:

Scribancustomfunc9

 

Let’s check the preview:

Scribancustomfunc10

 

ERROR

Now the error says that “Invalid number of arguments 0 passed to sc_get_settings while expecting 1 arguments”. Now go up and check the signature of our Function. We need to pass a string that will be assigned to settingName parameter. Lets show the value of AuthorName setting. In Scriban, we do it as follows:

Scribancustomfunc11

Preview the changes:

Scribancustomfunc12

 

 

 

Let’s access all Settings:

Scribancustomfunc13

 

Check the preview:

Scribancustomfunc14

 

(Sorry Guys, I have not focused much on Frontend best practices related to HTML and Presentation.)

 

This article was all about adding a custom Embedded function that will return the Settings value in Scriban. This can be used full in many scenarios as it gives the developer a way to add and customize information accessible in Scriban.

]]>
https://blogs.perficient.com/2020/08/03/sxa-scriban-creating-custom-embedded-function-in-scriban/feed/ 0 278212
Sitecore Powershell 7: Creating Reports https://blogs.perficient.com/2020/05/28/sitecore-powershell-7-creating-reports/ https://blogs.perficient.com/2020/05/28/sitecore-powershell-7-creating-reports/#respond Thu, 28 May 2020 16:03:51 +0000 https://blogs.perficient.com/?p=274554

One scenario you may encounter is wanting to create a report containing information about our Sitecore instance and its content. In this blog, we will see a few methods of how we can create reports using Sitecore Powershell.

Exporting Data as Plain Text File Using Out-Download Command

The Out-Download command is used to prompt the Browser client to download the generated output stored in the file named using –Name parameter. We need to specify input data using –InputObject.

Following is the script that will export information about the items that refer to item with ID – {13AAD693-D140-4054-840D-4F9DABF681D3} and are created from Event Details template.

 

#Exporting information in plain text

[String[]] $data = Get-ItemReferrer -ID "{13AAD693-D140-4054-840D-4F9DABF681D3}" | Where-Object { $_.TemplateName -eq "Event Details" } | Select-Object -Property Name,Id, TemplateName

 Out-Download -Name ReferrerInfo.txt -InputObject $data

See that $data is of type String[], and the –Name parameter of Out-Download command has a file name with an extension .txt. After running the script, I was prompted to download a file named ReferrerInfo.txt and inside it, I found Item object information as Powershell Hash tables in plain text.

Following are the downloaded file’s content:

    Spereports1

Exporting Data as Excel File Using Out-Download Command

The exported file had raw objects in plain text which is readable only for a developer. We can instead use Out-Download command to export data as an Excel sheet in proper Excel format.

We will be using the ConvertTo-Xlsx function, which will apply the proper Excel native format. For using this function, we need to first Import it using the Import-Function command. After that, we just need to add ConvertTo-Xlsx command after a (|). Also, as this will not be a plain text, we will change the data type of $data to byte[].

#Export data as Excel sheet
Import-Function -Name ConvertTo-Xlsx

[byte[]] $data = Get-ItemReferrer -ID "{13AAD693-D140-4054-840D-4F9DABF681D3}" | Where-Object { $_.TemplateName -eq "Event Details" } | Select-Object -Property Name,Id, TemplateName | ConvertTo-Xlsx

 Out-Download -Name ReferrerInfo.xlsx -InputObject $data

 

After running the script and downloading ReferrerInfo.xlsx file, it had the following content:

Spereports2

 

You can see how properly structured it is with respect to a plain text files.

Exporting Data as CSV File Using Export-CSV Command

This command will create a CSV Format file based on the input provided and dump the CSV information in the file specified by –Path location.

#Export data to CSV in file disk
$DataLoc = "C:\testCSV\ComponentsInUse.csv"

Get-ItemReferrer -ID "{13AAD693-D140-4054-840D-4F9DABF681D3}" | Select-Object -Property Name,Id, TemplateName | Export-Csv -Path $DataLoc

This script will create a CSV file ComponentsInUse.csv inside C:\testCSV folder.

Following are the content of this file:

Spereports3

 

When opened in Excel:

Spereports4

 

So far, we have seen how to export item information in a simple text file, Excel file using Out-Download command, and how to use Export-Csv command to export information in CSV. In the next post of this series, we will see how to import CSV and create items from it.

]]>
https://blogs.perficient.com/2020/05/28/sitecore-powershell-7-creating-reports/feed/ 0 274554
Sitecore Powershell 6: Working with Item References https://blogs.perficient.com/2020/05/25/sitecore-powershell-6-working-with-item-references/ https://blogs.perficient.com/2020/05/25/sitecore-powershell-6-working-with-item-references/#respond Mon, 25 May 2020 15:55:29 +0000 https://blogs.perficient.com/?p=274545

We have seen scenarios where we want to know about Item references. For instance, suppose we want to get a list of items that have SideContent Rendering assigned to their presentation. This is the exact kind of information that we are going to extract using different commands detailed in this post.

One thing to note is that these commands will make use of Link Database, so your Link Database should be up-to-date.

Note: If you have not updated your Link Database, I recommend to update it before performing below operations using Sitecore Powershell.

Get-ItemReferrer

This command is used to get all the items that refer to the item specified in the command. So, suppose we want to get list of items that refer to our SideContent rendering. Following is the script that can accomplish that using Get-ItemReferrer:

 

Get-ItemReferrer -ID "{13AAD693-D140-4054-840D-4F9DABF681D3}" | Format-Table -Property Name,Id

Here, we are using the ID of our rendering to be used in Get-ItemReferrer command.

Output of the above script:

Spereference1

You can see the list has all kinds of items that refer to our rendering item.

We can use Where-Object to filter out our result set based on TemplateName. We only want to know the names of items created from Event Details Template that refer to our item.

Get-ItemReferrer -ID "{13AAD693-D140-4054-840D-4F9DABF681D3}"  | Where-Object { $_.TemplateName -eq "Event Details" }

 

Output of above command:

Spereference2

 

Get-ItemReference

This command will return a list of items that the specified item refers to. In other words, this command will retrieve a list of items that are referred by the specified item.

Let’s check what items are linked to Home Page item:

Get-ItemReference -ID "{D45691EA-32A0-44D3-B56C-7B70A0CFA65E}" | Format-Table -Property Name,Id, TemplateName

 

Output of the above:

Spereference3

 

Using -ItemLink with Get-ItemReference

Using -ItemLink will force the Get-ItemReference command to return a list of Links rather than Items where you can find more information about the association between your target item and source item.

 

Get-ItemReference -ID "{D45691EA-32A0-44D3-B56C-7B70A0CFA65E}" -ItemLink

 

Output after running the above command:

Spereference4

 

As you can see, the information retrieved after adding –ItemLink has information about link between target and source. Here you can find the Source Field ID and Target Item ID that is assigned to this field. Database, versioning information among others.

Let’s format out output a bit using Select-Object to output only Source Field ID and Target Item ID:

Get-ItemReference -ID "{D45691EA-32A0-44D3-B56C-7B70A0CFA65E}" -ItemLink | Select-Object -Property SourceFieldID,TargetItemID

 

Output of the above:

Spereference5

 

Update-ItemReferrer

Let’s suppose we have a scenario where we want to update all the references of the DecorationBanner image field from EventBanner image media item to NewEventBanner image media item.

$bannerImage = Get-Item -Path "master:" -ID "{ECDF3D59-73C1-41A3-9F87-ACD56900765F}"

$newImage = Get-Item -Path "master:" -ID "{1CBD0EE7-0CD5-4A8B-8626-EDB0F0599A5F}"

$bannerImage | Update-ItemReferrer -NewTarget $newImage

 

In the above script, we are taking the current banner image item and the new banner image item in separate variables. Then, we are performing Update-ItemReferrer command with $bannerImage as input and -NewTarget specified with $newImage.

But, we have one problem here. This is a global operation as there is no filtering performed here. What if you only want them to be updated in items created from Event Details template? This will require us to write some custom script that will provide filtered input to Update-ItemReferrer command. We will only include children and grandchildren of Home Page items which are created from Event Details template. Then, we will use –ItemLink and Where-Object (?) to get link information of only fields which refer to $bannerImage media item. And then we will be passing it to Update-ItemReferrer command as input.

Following will be the script that we will be using to filter as per our requirement:

$bannerImage = Get-Item -Path "master:" -ID "{ECDF3D59-73C1-41A3-9F87-ACD56900765F}"

$newImage = Get-Item -Path "master:" -ID "{1CBD0EE7-0CD5-4A8B-8626-EDB0F0599A5F}"

$EventDetailItems = Get-ChildItem -Path "master:" -ID "{D45691EA-32A0-44D3-B56C-7B70A0CFA65E}" -Recurse | Where-Object { $_.TemplateName -eq "Event Details" }

$EventDetailItems | Get-ItemReference -ItemLink | Where-Object { $_.TargetItemID -eq $bannerImage.ID }


 

Output of the above:

Spereference6

 

As you can see, we only have 4 rows in our result because we only have 4 items created from Event Details template under Home Page. Also, you can see that the table shows information about link because we used –ItemLink. You will also notice that the TargetItemID is the same. This is because we filtered the result based on ID of our EventBanner media item.

Now, as we are done with our filtering, let’s add Update-ItemReferrer command to our script and pass our filtered list as input.

The script would be then:

#Get reference to current a target image item

$bannerImage = Get-Item -Path "master:" -ID "{ECDF3D59-73C1-41A3-9F87-ACD56900765F}"
$newImage = Get-Item -Path "master:" -ID "{1CBD0EE7-0CD5-4A8B-8626-EDB0F0599A5F}"


#Filter our result based on parent node and TemplateName
$EventDetailItems = Get-ChildItem -Path "master:" -ID "{D45691EA-32A0-44D3-B56C-7B70A0CFA65E}" -Recurse | Where-Object { $_.TemplateName -eq "Event Details" }

$LinkList = $EventDetailItems | Get-ItemReference -ItemLink | ? { $_.TargetItemID -eq $bannerImage.ID }




#Execute Update-Referrer command on filtered result set
$LinkList | Update-ItemReferrer  -NewTarget $newImage

 

I executed the above script. There would be no output as its updating the links so to check if our field has been updated, I ran this script:

Get-ChildItem -Path "master:" -ID "{D45691EA-32A0-44D3-B56C-7B70A0CFA65E}" -Recurse | Where-Object { $_.TemplateName -eq "Event Details" } | ForEach{
    $_._.DecorationBanner.MediaID

}

 

Output of above:

Spereference7

 

As you can see from the above image, our DecorationBanner field has been updated with $newImage item.

We saw how we can use Get-ItemReferrer, Get-ItemReference and Update-ItemReferrer in this post. These are very useful commands when we want to extract and manipulate information of item references.

The next post will be about how we can use Sitecore Powershell commands to create reports and export them.

 

 

 

 

 

 

 

]]>
https://blogs.perficient.com/2020/05/25/sitecore-powershell-6-working-with-item-references/feed/ 0 274545
Sitecore Powershell 5: Working with Renderings https://blogs.perficient.com/2020/05/22/sitecore-powershell-5-working-with-renderings/ https://blogs.perficient.com/2020/05/22/sitecore-powershell-5-working-with-renderings/#comments Fri, 22 May 2020 15:34:02 +0000 https://blogs.perficient.com/?p=274538

Renderings are one of the most important parts of the Sitecore Presentation. With Sitecore Powershell, we can extract information about renderings that are attached to particular item. Let’s see different commands that can be used to extract and manipulate the rendering information of an item.

Get-Rendering

Using this command, we can get the information about all the renderings that has been assigned to an items presentation. We can specify Path, ID or an object of Item in this command from which we want to extract rendering information. We can also specify Layout Device using Get-LayoutDevice to get device information. Following is the command that we are going to run:

$deviceObj = Get-LayoutDevice -Default

Get-Rendering -Path "master:/sitecore/content/Events/Home Page/Events/Climbing/Climb Mount Everest" -Device $deviceObj -FinalLayout

 

The item that resides in the path above has following renderings:

  1. RelatedEvents
  2. SideContent
  3. EventIntro
  4. PageContent

 

Output after running above script:

Image1

You can see that the information in the output has many properties like ItemID, OwnerItemID, Datasource, Placeholder, etc.

This is the presentation specific information about renderings attached to our page item.

Let us format this information by using Format-Table command:

$deviceObj = Get-LayoutDevice -Default
$resultObj = @()
Get-Rendering -Path "master:/sitecore/content/Events/Home Page/Events/Climbing/Climb Mount Everest" -Device $deviceObj -FinalLayout | ForEach {
    $renderingItem = Get-Item -Path  master: -ID $_.ItemID

    $Obj = @{
        RenderingName =  $renderingItem.Name
        Placeholder = $_.Placeholder
        PageItem = $_.OwnerItemID
    }

    $resultObj += New-Object psobject -Property $Obj
}

$resultObj | Format-Table RenderingName, Placeholder, PageItem

 

Output of above script:

Image2

Here,

@() -> initializes and empty array

@{} -> used to create a hash table (Let’s assume a key-value pair anonymous object)

New-Object psobject -Property $Obj -> This line creates a new object of type psobject from our hash table created from @{} and appends it to our result array

 

Finally, we use our resultObj as input to Format-Table.

 

Set-Rendering

This command is used to update rendering related information in an item’s presentation. For this, we will need the Rendering item first, which we can get using Get-Rendering command.

Let’s see how we can change the rendering properties of an item:

The following script will change the placeholder of all the renderings in “PageSide” placeholder to “main.”

$path = "master:/sitecore/content/Events/Home Page/Events/Climbing/Climb Mount Everest"
$deviceObj = Get-LayoutDevice -Default
Get-Rendering -Path $path -Device $deviceObj -FinalLayout -PlaceHolder "pageSide" | ForEach{
        $_.Placeholder = "main"
        Set-Rendering -Path $path -Instance $_
}

 

Output of the above:

Image3

See the placeholder has been changed to “main.” We used -Instance parameter to pass updated rendering objects. In our case, we used ForEach to loop through all the renderings in “pageSide” placeholder hence each iteration was capture in $_ object. Which we used to update Placeholder and passed it to -Instance.

 

Add-Rendering

This command is used to add rendering to the presentation of an item. We will be using New-Rendering command to create a presentation attachable rendering object from the Rendering Definition item.

Following is the script to add a rendering with ID {13AAD693-D140-4054-840D-4F9DABF681D3} to the “About Us” page item’s final layout.

Following is the script:

 

$renderingItemID = "{13AAD693-D140-4054-840D-4F9DABF681D3}"

$rendering = Get-Item -Path "master:" -ID $renderingItemID | New-Rendering -Placeholder "pageSide"

$rendering.Datasource = "{60F991D6-9172-4456-A5F9-908E3DDA0A51}"

$item = Get-Item -Path "master:/sitecore/content/Events/Home Page/About Us"

Add-Rendering -Item $item -PlaceHolder "pageSide" -Instance $rendering -FinalLayout

 

Here we are also specifying data source using $rendering.Datasource.

 

Output of the above script:

Image4

You can see that our rendering has been added to the presentation of About Us item.

 

Remove-Rendering

As the name suggests, it will remove the renderings from the presentation of the item specified in the command. Most of the parameters like -Placeholder, -Device, -Datasource, -Instance, -Parameter, etc. will act as filter criteria for the deletion of renderings.

The following script removes renderings from Final layout assigned to pageSide placeholder:

 

$item = Get-Item -Path "master:/sitecore/content/Events/Home Page/About Us"

#Delete the renderings that have been assigned to pageSide placeholder
Remove-Rendering -Item $item -Placeholder "pageSide"

Get-Rendering -Item $item -FinalLayout

 

Output of the above script:

Image5

 

The output is blank because the Get-Rendering command did not find any rendering assigned to the About Us item as we have deleted the previously assigned renderings using Remove-Rendering command.

In this post, we have seen how we can use different Sitecore Powershell commands to work with Renderings. In the next post, we will see the concept of extracting Item Reference information using Sitecore Powershell and how we can use it to get all the items that refer to a particular item.


READY TO GROW YOUR CAREER?

Perficient continually looks for ways to champion and challenge our workforce, encourage personal and professional growth, and celebrating our people-oriented culture. Work on interesting projects for some of the world’s most recognizable clients and enjoy life while doing so.

Learn more about what it’s like to work at Perficient at our Careers page. See open jobs or join our community for career tips, job openings, company updates, and more!

Go inside Life at Perficient and connect with us on LinkedIn and Twitter.

]]>
https://blogs.perficient.com/2020/05/22/sitecore-powershell-5-working-with-renderings/feed/ 1 274538
Sitecore Powershell 4: Using ContentSearch API with the Help of Find-Item https://blogs.perficient.com/2020/05/20/sitecore-powershell-4-using-contentsearch-api-with-the-help-of-find-item/ https://blogs.perficient.com/2020/05/20/sitecore-powershell-4-using-contentsearch-api-with-the-help-of-find-item/#comments Wed, 20 May 2020 13:36:52 +0000 https://blogs.perficient.com/?p=274120

In previous posts of this blog series, we have seen how we can use Get-Item and Get-ChildItem to fetch items from our Sitecore instance. Get-ChildItem command is very slow if we have a large number of items to fetch. This is the same when we try to fetch a large number of items by using the Sitecore Item API. The use of Sitecore ContentSearch API is highly recommended for this scenario.

The same is correct for Sitecore Powershell. We can use features provided by Sitecore’s ContentSearch API in our Powershell Scripts.

 

Find-Item

Find-Item cmdlet is used to fetch items using ContentSearch API, where we provide the name of the index and filtering conditions before getting the results. The results that are returned are of type SearchResultItem; however, we can leverage the use of another cmdlet that lets us include our custom fields in the result set.

Following are a few parameters that we can use with Find-Item:

  1. -Index: Where we specify the name of the index to use.
  2. -Criteria: Where we specify the Search Filter
  3. -First: Where we can specify the number of results to return
  4. -Skip: Where we can specify the number of results to be skipped before returning the result
  5. -Where: Where we can specify Dynamic Linq to filter results
  6. -WhereValue: Where we can specify Array of values that will be used by -Where Linq statement

Let’s execute one example script to see how Find-Item works:

 

$FilterCriteria = @(

    @{Filter = "Equals"; Field = "_templatename"; Value = "Event Details"},

    @{Filter = "StartsWith"; Field = "_fullpath"; Value = "/sitecore/content/Events" }

)




Find-Item -Index "sitecore_master_index" -Criteria $FilterCriteria

 

See that we have specified “sitecore_master_index” for –Index parameter. We have created a Grouping expression and assigned it to $FilterCriteria variable.

Then, we created different Filters of objects inside our Criteria expression. Every Filter has three imp parts: Field, Filter, and Value.

  • Filter: Where we specify the operator for evaluating the condition. Ex- Equals, StartsWith, Contains, EndsWith, LessThan, GreaterThan etc.
  • Field: Where we can specify the name of the indexed field that we want to use in filtering condition.
  • Value: Value of the field for satisfying the condition.

 

Output of the above Script:

Finditeam

 

Above, the script will get the result which has the TemplateName property value as Event Details and their path starts with “/sitecore/content/events” as shown in the image.

 

Fetching Custom Fields

Now, as I have mentioned, the result set will contain an item of type SearchResultItem. We will not get our custom fields if we try to access them.

 

See the below image where I have written a script to display Custom Field DifficultyLevel. It does not show anything.

Fetchingcustomfield1

 

Here, we can use Initialize-Item after Pipe operator in our statement to get custom fields in our results.

Using the following script displayed our custom field in result output:

 

$FilterCriteria = @(

    @{Filter = "Equals"; Field = "_templatename"; Value = "Event Details"},

    @{Filter = "StartsWith"; Field = "_fullpath"; Value = "/sitecore/content/Events" }

)




Find-Item -Index "sitecore_master_index" $FilterCriteria | Initialize-Item | Select-Object -Property DifficultyLevel

 

 

Output of above:

Fetchingcustomfield2

Here, we can now see the values for our custom fields. Initialize-Item transforms SearchResultItem type items in the result set to Sitecore Items with all the fields included.

 

Using -First

We can use -First operator to fetch a given number of result items from the result set. Following is the statement:

$FilterCriteria = @(

    @{Filter = "Equals"; Field = "_templatename"; Value = "Event Details"},

    @{Filter = "StartsWith"; Field = "_fullpath"; Value = "/sitecore/content/Events" }

)




Find-Item -Index "sitecore_master_index" -Criteria $FilterCriteria -First 2

 

This will only fetch 2 items from the result set:

Firstentry

 

 

Using -Skip Operator

This will skip the number of items based on the value we pass.

$FilterCriteria = @(

    @{Filter = "Equals"; Field = "_templatename"; Value = "Event Details"},

    @{Filter = "StartsWith"; Field = "_fullpath"; Value = "/sitecore/content/Events" }

)




Find-Item -Index "sitecore_master_index" -Criteria $FilterCriteria -Skip 2

 

 

Output:

Skipentry

 

 

Using Where and WhereValues

We can use Where and WhereValues to filter our search instead of Criteria. Here we can use proper objects as opposed to Criteria operator that we saw previously. –Where is used to specify Dynamic Linq query and –WhereValues contains array of values.

Following, the script will fetch items based on Templates that have “Event” in their name and which are under “/sitecore/content/events” node.

 

$WhereCondition = 'TemplateName.Contains(@0) And Path.Contains(@2)'

$WhereValues = @("Event", "en","/sitecore/content/Events")

Find-Item -Index "sitecore_master_index" -Where $WhereCondition -WhereValues $WhereValues

 

 

Output of Above Script:

Wherefinditem

 

 

In this blog post, we have seen how we can query Sitecore indexes using ContentSearch API in Sitecore Powershell. This is a fast approach and we can use filters easily for our result.

So far we have seen how to work with Sitecore Items. In the next post, we will learn about how we can work with Sitecore Renderings using different Sitecore Powershell commands.

]]>
https://blogs.perficient.com/2020/05/20/sitecore-powershell-4-using-contentsearch-api-with-the-help-of-find-item/feed/ 4 274120
Sitecore Powershell 3: Filtering the Result Set Using Where-Object https://blogs.perficient.com/2020/05/16/sitecore-powershell-3-filtering-the-result-set-using-where-object/ https://blogs.perficient.com/2020/05/16/sitecore-powershell-3-filtering-the-result-set-using-where-object/#comments Sat, 16 May 2020 13:28:02 +0000 https://blogs.perficient.com/?p=274110

In the previous post, we saw how to use Get-Item and GetChildItem to retrieve information about Sitecore items. These are useful when we want every item that fits under the given Path to be retrieved. Now, let’s discuss more about what problems can be solved using Where-Object.

Get-ChildItem cmdlet retrieves a list of children of a given node. We can also use –Recuse to get all of its descendants. What if we want to add a filter or provide a condition to filter out items that we do not want in our result?

We can achieve this by using Where-Object cmdlet separated by Pipe (|). Following is the statement of how we can filter our result set based on TemplateName where TemplateName is Event Details.

Get-ChildItem -Path master:\content\events -Recurse | Where-Object { $_.TemplateName -eq "Event Details"}

 

This will filter and return a result that contains items created from Event Details template only. We can pass our filter condition inside a script block. Here we are using -eq operator.

You will notice that we are using $_.TemplateName. Here, $_ is nothing but a token that is used to refer to items inside a loop or here each item inside our result set.

 

It works similar to C# Lambda Expression in Linq.

For Example, $_ is same as i in i => i.Name.Contains(“Events”)

 

Now, after executing the above statement, we get the following filtered result:

Whereobject

See the TemplateName column. We only got the entries that have Event Details in TemplateName. We have used -eq in our condition, but there are many other useful conditional cmdlets that we can use in Where-Object. Lets see some of them.

 

-ne Operator

This is “not equal to” the operator that we can use in our Condition script block of Where-Object. Following is the statement to include items in the result set which are not created from Event Details template.

Get-ChildItem -Path master:\content\events -Recurse| Where-Object { $_.TemplateName -ne "Event Details"}

 

 

Output for above:

Notequal

You can see that the output list does not contain any items that have Event Details in TemplateName.

 

-Like

This operator can be used to match a value using wildcards where we can specify Starts with, Ends with, or contains type conditions.

Following is a statement which returns the list of items that has “Event” as substring in TemplateName property.

Get-ChildItem -Path master:\content\events -Recurse| Where-Object { $_.TemplateName -like "*Event*"}

 

Output of the above statement:

Like

 

 

-gt Operator

This is Greater than operator (>). We can use this to compare numerical values. I used it to compare DifficultyLevel field of Event Details items. Following is the statement:

Get-ChildItem -Path master:\content\events -Recurse| Where-Object { $_.DifficultyLevel -gt 3}

 

Executing the above statement will return the result containing items that have DifficultyLevel field value greater than 3.

 

Output of above statement:

Greaterthan

 

You can see that the list returned has only two items. Let’s include DifficultyLevel Field in our output, which is a numeric field. This time, we will not be using Format table. Instead, we will use Select-Object to select only specific fields to display.

The main feature of using Select-Object is that we can show calculated values in our result set but here we will only be using it to display out selected field.

Following is the modified statement with Select-Object:

Get-ChildItem -Path master:\content\events -Recurse | Where-Object { $_.DifficultyLevel -gt 3} | Select-Object -Property Name, DifficultyLevel, TemplateName

 

Output of the above statement:

Whereselectobject

 

You can see in the image that those two results have DifficultyLevel field value as 4 and 5 which are greater than 3.

Note: Less than operator -lt works opposite as it is less than operator.

 

 

Logical operators -And and -Or

We can use logical operator And and Or in our Where-Object conditions. Following is the statement that uses them. This statement will return a result containing items that are not created from Event Details template nor from Event Lists template.

Get-ChildItem -Path master:\content\events -Recurse| Where-Object { $_.TemplateName -ne "Event Details" -and $_.TemplateName -ne "Event List"}

 

Output of the above:

 

Andcondition

 

In this post we saw how to filter our result set using Where-Object. Till now, we were using normal commands to get item information. These commands fetch data from Sitecore Databases. In the next post, we are going to see how we can query Sitecore indexes using ContentSearch API.

 

]]>
https://blogs.perficient.com/2020/05/16/sitecore-powershell-3-filtering-the-result-set-using-where-object/feed/ 2 274110
Sitecore Powershell 2: Retrieving Item Information https://blogs.perficient.com/2020/05/14/sitecore-powershell-2-retrieving-item-information/ https://blogs.perficient.com/2020/05/14/sitecore-powershell-2-retrieving-item-information/#respond Thu, 14 May 2020 13:37:39 +0000 https://blogs.perficient.com/?p=274096

In my last post, I gave an overview of Sitecore Powershell and how to install the Sitecore Powershell Extension. Sitecore Powershell can also be used to work with Sitecore items. In this blog, we will see how we can use it to retrieve information about items in our content tree. We would be using Get-item and Get-ChildItem cmdlets.

A cmdlet is a lightweight command that is used in the PowerShell environment. It acts as a lightweight Powershell script that performs a specific action.

Below is the image of how my site structure looks:

Eventnode

 

Now, let’s open the Powershell ISE and start to create our script.

 

Using Get-Item cmdlet

  1. Used to retrieve a single item.
  2. We will be using -Path, -Language and -Version
  3. -Path is used to specify the path of the item that we want to retrieve.
  4. -Language is used to specify which language version of the item we want to retrieve.
  5. -Version is used to specify which numbered version of an item we want to retrieve.

 

Get Information About A Single Item Using Get-Item

Write the Get-Item command as mentioned below and pass your item path, as I have passed the path to my events item.

 

Get-Item -Path "master: \content\events"

 

After you have written this command and specified the path to your item, click on the Execute button in the toolbar. Following is the output that I got after executing.

Getitemevent

Note: You will need elevated access/login to execute scripts.

 

Get Language-Specific Version of an Item

We can use –Language to specify which language version of a particular item we want to retrieve. Following is the command that I used to get the German version of my events item.

Get-Item -Path master: \content\events -Language de-DE

 

I can see the below information after execution.

Getitemlang

 

You can see that I am getting both the English version and the German version of my events item. This is because Execute works on the whole script and not just one statement. So, it will execute both our statements.

If we want only our second statement to execute, we need to select the statement and use the Selection button to execute it. Using the Selection button produced the below output:

Selection

 

Get Specific Numbered Version of an Item

We can use –Version for specifying which numbered version we want for an item. Specify the number after –Version. Following will retrieve version 2 of our events item:

Get-Item -Path master: \content\events -Version 2

 

The output is as below:

Getitemnumberversion

 

 

Get all Language and Numbered Versions of an Item

We can use * after both –Language and -Version in our command to get all language or numbered versions. We can also use both –Language and -Version in our command at the same time to get every version of our item:

Get-Item -Path master: \content\events -Language * -Version *

 

Below is the output for executing the above command:

Getitemversionall

 

Get Items Using ID

You can also fetch an item by passing ID in Get-Item. Following is the syntax to do it:

Get-Item -Path master: -ID “SpecifyYouIDHere”

 

Following is the output when I specify ID of my Home Page item:

Getitemid

 

Using Get-ChildItem cmdlet

We can use Get-ChildItem to get a list of child items of a node that we will specify using –Path. Following is the command that will retrieve child items of my events node.

Get-ChildItem -Path master: \content\events

 

Following is the output after execution:

Getchilditem

 

You can see that it only retrieved first-level children of Events node. If we want a list of an item’s children and grandchildren, we need to add -Recurse. This will retrieve children recursively.

Get-ChildItem -Path master: \content\events -Recurse

 

Below is the output:

Getchilditemrecurse

 

Format the Output View

We can format the output to include the information that we want. We will be using Pipe (|) for achieving this. We use | to specify that result of the first statement will be used as input for the second one that comes after | character.

We will be formatting our output to include DisplayName, Creation timestamp, TemplateName, and ContentHeading field. Following is the command to do that:

Get-ChildItem -Path master:\content\events | Format-Table -Property DisplayName, ContentHeading, Created, TemplateName

See how we have used Pipe (|) in the above command. It works like this – Use the output of Get-ChildItem cmdlet before | as input to Format-Table cmdlet.

So, the children list of Events node is used as input in Format-Table command which use -Property arguments to filter the fields that will be included in the output table.

Below is the output after executing the above command:

Formattable

 

Count the Objects in the Result Set

We can use Measure-Object to get the total count of objects in the returned result set. Using the following statement, I can get the count of items in our result set:

Get-ChildItem -Path master:\content\events -Recurse| Measure-Object

 

Output:

Measureobject

 

In this article, we have seen how to fetch a particular item using path or ID, how to fetch a list of children, and how too format output according to our needs. In the next blog, we will be exploring about accessing fields and looping through each item in the Children list.

Learn more about Sitecore from our blog.

 

 

]]>
https://blogs.perficient.com/2020/05/14/sitecore-powershell-2-retrieving-item-information/feed/ 0 274096
Sitecore Powershell Extension 1: Installation and Overview https://blogs.perficient.com/2020/05/06/sitecore-powershell-extension-1-installation-and-overview/ https://blogs.perficient.com/2020/05/06/sitecore-powershell-extension-1-installation-and-overview/#respond Wed, 06 May 2020 16:58:29 +0000 https://blogs.perficient.com/?p=274085

The Sitecore Powershell Extension is a module that provides a command-line interface and scripting environment to work with the Sitecore platform. Using the Powershell Extension, we can perform various operations of Sitecore items, as well as allow access to Sitecore APIs. It looks and works in the same way as the Windows Powershell utility.

Sitecore Powershell Extension is not installed out of the box, therefore, we need to install it separately.

 

Installing the Sitecore Powershell Extension Module

  1. Go to http://marketplace.sitecore.net/ and download the package for Sitecore Powershell Extension for your Sitecore instance.
  2. Install the downloaded package in your instance.
  3. After successful installation, you will see the following additions to your Launchpad and Desktop.

 

Launchpad

sitecore powershell extension

Desktop

powershell console and toolbox

 

Tools that Come With the Sitecore Powershell Extension Module

 

  1. Powershell Console

Powershellconsoole

This tool provides a simple command-line interface in the same way as our Windows Powershell. You can enter a single command at a time and see the output.

 

  1. Sitecore PowerShell Integrated Scripting Environment (Powershell ISE)

Powershellise

The Sitecore PowerShell ISE is a tool that can be used to create, edit, test, and execute PowerShell scripts. The Sitecore Powershell ISE offers a very advanced and flexible scripting environment.

ISE adds a GUI and more functions. Following are some of the functions that it provides over Powershell Console:

  1. Saving Powershell scripts and the ability to open them later
  2. Executing scripts with on click
  3. Switching the current database
  4. Switching the current user and language
  5. Debugging
  6. Ability to execute selected part of the script

Interface of Powershell ISE

interface of powershell

You can see all the options in the menu divided into sections which are named Write, Script Execution, Context, UI Context, and About.

Now, if your Sitecore Powershell Extension package is installed, you can go ahead and open Powershell ISE tool and execute the script to output “Hello World” as shown in the image above.

Useful Links:

  1. https://github.com/SitecorePowerShell/Console
  2. https://doc.sitecorepowershell.com/

This was just a basic introduction to the Sitecore Powershell Extension module and SPE tools that gets installed with the package. In the next post, we are going to see how we can fetch item information using different Sitecore Powershell Commands.

]]>
https://blogs.perficient.com/2020/05/06/sitecore-powershell-extension-1-installation-and-overview/feed/ 0 274085
Sitecore Experience Accelerator (SXA) 9.3: Scriban Template in Rendering Variant https://blogs.perficient.com/2019/12/27/sitecore-experience-accelerator-sxa-9-3-scriban-template-in-rendering-variant/ https://blogs.perficient.com/2019/12/27/sitecore-experience-accelerator-sxa-9-3-scriban-template-in-rendering-variant/#comments Fri, 27 Dec 2019 14:00:45 +0000 https://blogs.perficientdigital.com/?p=242163

One of the main features in Sitecore SXA 9.3 is the introduction of Scriban Templates. This will replace the legacy NVelocity Template engine that was being used previously with SXA. Scriban is very efficient when it comes to performance and flexibility.
 
SXA Scriban Template gif
 
We can define HTML structure using Scriban with usage of extra properties. These properties can be used to read Sitecore item data. We can replace a whole component by using Scriban for small requirements. We can do this using for loops, conditional statements, and embedded functions provided by Scriban Templating language.
 
 

Let’s See How We Can Use It

 
We will be creating a rendering variant of the Page Content component to include a Scriban Template containing our custom markup. In the markup, we will be using different Scriban embedded items and objects that we can use to display different properties of Sitecore context and Sitecore items using Scriban Template language’s embedded items, objects, and functions.
1. Go to /sitecore/content/DemoTenant/TestSite/Presentation/Rendering Variants/Page Content and create a Variant definition item named “Scriban Content”.
2. Now, inside Scriban Content node, insert an item of Scriban type and name it “Scriban”.
 
, insert an item of Scriban type
 
3. Now select the desired container tag in Tag field and put the markup from below in Template.
 
select the desired container tag
 
 

<div>
<h1>Item properties</h1>
<h2> This is <b>i_item.name</b> {{i_item.name}}</h2>
<p><b>i_home</b> {{i_home}}</p>
<p><b>i_datasource</b> {{i_datasource}}</p>
<p><b>i_datasource.name</b> {{i_datasource.name}}</p>
<p><b>i_site.name</b> {{i_site.name}}</p>
<p><b>i_page.name</b> {{i_page.name}}</p>
<p><b>i_site</b> {{i_site}}</p>
<p><b>i_item.title</b> {{i_item.title}}</p>
<p><b>i_item.content</b> {{i_item.content}}</p>
<p><b>i_item.parent</b> {{i_item.parent}}</p>
<p><b>i_item.template_id</b> "{{i_item.template_id}}"</p>
<p><b>i_item.has_children</b> {{i_item.has_children}}</p>
<p><b>i_item.path</b> {{i_item.path}}</p>
<p><b>i_item.url</b> {{i_item.url}}</p>
<br><br>
<h1>Useful Scriban objects</h1>
<h1>Context Object</h1>
<p><b>o_context.database</b> {{o_context.database}}</p>
<p><b>o_context.user</b> {{o_context.user}}</p>
<p><b>o_context.user.name</b> {{o_context.user.name}}</p>
<p><b>o_context.domain</b> {{o_context.domain}}</p>
<p><b>o_context.is_administrator</b> {{o_context.is_administrator}}</p>
<p><b>o_language</b> {{o_language}}</p>
<h1>Page Mode</h1>
<p><b>o_pagemode.is_experience_editor</b> {{o_pagemode.is_experience_editor}}</p>
<p><b>o_pagemode.is_preview</b> {{o_pagemode.is_preview}}</p>
<p><b>o_pagemode.is_normal</b> {{o_pagemode.is_normal}}</p>
<br><br>
<h1>Some basic Scribban functions</h1>
<p><b>sc_link using current item to render link</b></p>
<a href="{{ sc_link i_datasource }}">{{ i_datasource.display_name }}</a>
<br>
<p><b>sc_parameter retrieves Rendering Parameter values | '{{ sc_parameter 'Placeholder' }}' </b></p>
<div>This rendering is added to {{ sc_parameter 'Placeholder' }} placeholder.<div>
</div>

 
 
4. Next, open your page item in Experience Editor and drop Page Content component and then, from the Variant dropdown, select “Scriban Content”.
 
Scriban Content
 
5. Then, you will see different properties from Sitecore items being displayed.
6. We have used the following Scriban Embedded objects, items, and a few functions:

    1. i_home
    2. i_datasource
    3. i_site
    4. i_page
    5. i_item
    6. o_context
    7. o_language
    8. o_pagemode
    9. sc_link
    10. sc_parameter

 
 

Final Output

 
final output
 
In the end, Scriban Templates are a great way of rendering a custom markup with Sitecore properties that can be displayed without the necessity of coding.

]]>
https://blogs.perficient.com/2019/12/27/sitecore-experience-accelerator-sxa-9-3-scriban-template-in-rendering-variant/feed/ 3 269833
Sitecore Experience Accelerator (SXA) Rendering Variants: Using Custom Tokens https://blogs.perficient.com/2019/12/19/sitecore-experience-accelerator-sxa-rendering-variants-using-custom-tokens/ https://blogs.perficient.com/2019/12/19/sitecore-experience-accelerator-sxa-rendering-variants-using-custom-tokens/#comments Thu, 19 Dec 2019 14:00:06 +0000 https://blogs.perficientdigital.com/?p=242026

We have learned the basics of SXA’s Rendering Variants feature, and have seen how useful the feature is in terms of changing the appearance of our Components. This is very helpful when we want to use the same rendering to display different fields and many other properties like CSS Classes, HTML wrapper element, Data attributes, Link Attributes, etc.
There are many out of the box renderings provided by SXA that support rendering variants. In this post, we will be using the Page Content rendering to display value from a custom token.
 
 

What Are Custom Tokens in SXA’s Rendering Variant?

 
Imagine a scenario where you want to have a Rendering Variant (RV) that can show data from a third-party API call. In this situation, we cannot use the simple RV as we do not have these values coming from a Sitecore Context item. Another case would be when we want to manipulate the existing field values before displaying it. For instance, adding a query parameter to a URL link. In cases like these, we can use Custom Tokens to display complex data that cannot be displayed with normal rendering variant items.
To achieve this, we would be adding our own Token processer to the resolveVariantTokens pipeline.

 
 
 
 

Create a Class for Your Custom Token Resolution

 
1. Add XA.Foundation.Variants.Abstractions to your project using NuGet package.
2. Create a CS file for your Token Processor and add a reference to XA.Foundation.Variants.Abstractions.Pipelines.ResolveVariantTokens namespace.
3. If you are facing an error that Sitecore.XA Namespace not found, then remove the following <IncludeAssets> line from the csproj file.
 
remove <IncludeAssets>
 
4. Make your class inherit from ResolveVariantTokensProcessor as shown in the image below.
 
ResolveVariantTokensProcessor
 
5. As you can see in the image, we will be overriding Token property to provide our custom token name.
6. Our custom Token will now display “Hello World!! This is value from SXA Token” when used in a Rendering Variant.

 
 
 
 

Register Token Processor with resolveVariantTokens Pipeline Using Config Patch

 
1. Create a patch file to register your processor with the resolveVariantTokens pipeline as below.
 
resolveVariantTokens pipeline
 
2. Publish your solution and load Sitecore. Our next step is to create a Rendering Variant item with token variant field.
 
custom token gif

 
 
 
 

Create a Rendering Variant Definition Item

 
1. Navigate to /sitecore/content/Main/Website/Presentation/Rendering Variants/Page Content.
2. Right-click on Page Content node and add a Variant Definition item and name it Custom Test Token.
3. Now it’s time to add a Token Variant field to our Rendering Variant Definition item. Right-click on the Custom Test Token node and add Token type item named Test Token.
5. Now, in the Token field of our Test Token item, put $testtoken as this is the same value that we provided to the Token property in our ResolveTokenValue processor class.
 
$testtoken

 
 
 
 

Verify the Changes

 
1. Now, use the Experience Editor to drop the Page Content Rendering into your page and select the Custom Test Token Variant from the Variant Dropdown on the Toolbar.
2. You will see that the Token field now displays the string provided in the ResolveToken method of our processor class.
 
verify changes

 
 
 

Use of ASP.NET Server Controls for Custom Token

 
1. We can use any valid ASP.NET server control for rendering data.
 
ASP.NET server control
 
2. I used LiteralControl, but you can also add HtmlAnchor to the ResultControl for Links.

 
 
 

Changing Outer <span> for Custom Token

 
1. We can also change ResultControl to change outer <span> to any other element as Token by default use <span> tag to render. Although it is not necessary, sometimes we may have issues with HTML structure and CSS if we have any <div> inside <span>.
 
change args.ResultControl
 
2. ResultControl is of type HtmlGenericControl. So, we can change it by doing the following to change the <span> to any other element.
 
change the <span>
 
3. This will change the <span> to <div>.
 
change the <span> to <div>
 
 
This concludes our post on using Custom Token in our Rendering Variants. We hope you enjoyed this series on Rendering Variants with Sitecore SXA. Leave a comment below if this was helpful and let us know what Sitecore blogs you want to see next.

]]>
https://blogs.perficient.com/2019/12/19/sitecore-experience-accelerator-sxa-rendering-variants-using-custom-tokens/feed/ 2 269824
Sitecore Experience Accelerator (SXA) Rendering Variants: Wrap Link Field Around Another Field https://blogs.perficient.com/2019/12/12/sitecore-experience-accelerator-sxa-rendering-variants-wrap-link-field-around-another-field/ https://blogs.perficient.com/2019/12/12/sitecore-experience-accelerator-sxa-rendering-variants-wrap-link-field-around-another-field/#comments Thu, 12 Dec 2019 14:03:31 +0000 https://blogs.perficientdigital.com/?p=242017

As we covered in the first post on the basics of Rendering Variants in SXA, Rendering Variants are configurable adaptations of default renderings. With Sitecore Experience Accelerator (SXA), we can display many variations of a Component using Rendering Variants. In this blog post, we will look at the scenario where we want to wrap a link coming from a General Field around the content of a Rich Text field.
For this example, we will be using SXA’s Page Content Component. I have added the following fields to my Page Template, which I will use in our Rendering Variants to demonstrate how we can wrap a link from one field around another.
I have the following fields in my Page item:

  1. Page Title (Rich Text)
  2. Content (Rich Text)
  3. CTA Link (General Link)
  4. Wrapper Link (General Link)

Below, I populated all the fields as shown in the image:
field population

Now, go to the /sitecore/content/Main/Website/Presentation/Rendering Variants/Page Content and add a Variant Definition item named “Link Wrapped Content.
Now, in our Link Wrapped Content fill the “Field used as Link target” field with our Wrapper Link field name link on the following image.

Link Wrapped Content

Then, right-click on the Link Wrapped Content item and insert three Field type items named Page Title, Content, and CTA Link.
Field type items

Next, click on the item Named Content under our Variant Definition and check “Is Link” checkbox. “Is Link” checkbox will make sure that this field is rendered inside the Link element that we provided earlier in our Variant Definition’s “Field used as Link target” field.
Other fields which do not have “Is Link” checkbox checked will be rendered outside normally.

Is Link checkbox

We are now done creating our Rendering Variant.

Time to Test It!

Go to the Experience Editor and drop SXA’s Page Content component on the page. From the Variant dropdown, select our Variant Definition Link Wrapped Content. Here’s the resulting view of our Variant of Page Content Component.

Variant of Page Content Component

From the HTML structure from the below image, you can see that the content field is rendered inside a link element that has the URL of Wrapper Link field.

Wrapper link field

In the above post, we learned how to make a Rendering Variant that will render the content of a Rich text field inside as a Wrapper Link coming from another general link field. In the next part of this series, we will discuss using custom tokens in Rendering Variants.

]]>
https://blogs.perficient.com/2019/12/12/sitecore-experience-accelerator-sxa-rendering-variants-wrap-link-field-around-another-field/feed/ 1 269823
Sitecore Experience Accelerator (SXA) Rendering Variants: Basic Usage https://blogs.perficient.com/2019/12/04/sitecore-experience-accelerator-sxa-rendering-variants-basic-usage/ https://blogs.perficient.com/2019/12/04/sitecore-experience-accelerator-sxa-rendering-variants-basic-usage/#respond Wed, 04 Dec 2019 15:37:59 +0000 https://blogs.perficientdigital.com/?p=242006

Rendering Variants is one of the best features in Sitecore Experience Accelerator (SXA). The feature allows users to change the structure and appearance of how a Component will be rendered without needing any code changes. In this three-part series, we will look at a few different concepts of Rendering Variants. In this first post, we will look at the basics of Rendering Variants.
I’ll use an example to demonstrate just how useful Rendering Variants are.
 
Example Scenario
Suppose we want to have three variations of a Banner as follows:

  1. Simple Banner (Image only)
  2. Banner with Link

 

Solution without SXA

A traditional Sitecore approach would be to create three View Renderings for these scenarios. Then, a developer would have to create three components and associated code files. This would mean that adding and changing them would involve removing the previous component then adding a new one. Also in this solution, an author does not have the ability to change the structure. They cannot add HTML classes nor change the HTML element wrapper. So, to display a new field, code changes are required. In the end, without a developer, any structural change is impossible.

Solution with SXA

With SXA, we can use the Rendering Variants feature to change the structure and appearance of the Image component without creating new components for simple variations. We can use Rendering Variants and the author can specify CSS Classes, Add Data and Link attributes, Specify HTML wrapper element, Prefix and Suffix, etc. And, changing Rendering Variants is as simple as choosing the desired Variant from a Dropdown in the Component toolbar. This means we can display new fields without changing any code. Also, we can add JS Script, HTML Snippet, Wrapper sections, Placeholder, and many other Variant fields.
 

Rendering Variants in SXA: How It Works

Rendering Variants gif
First, let’s see the code inside Image Component view file found /views/Image/Image.cshtml. You will see that there is a foreach loop inside <div> tag with “component-content” class. This is where all the Fields included inside of a Rendering Variant definition are rendered.
 
Code inside Image Component
 
The RenderVariant extension method then returns the IHTMLString containing markup that will be rendered on the page.
 
IHTMLstring
 
Now, let’s create three Rendering Variants for three variations of our Banner Image. We will be using Image and TargetURL fields; which are Image type and General Link respectively.
 

Simple Banner (Image only) Variant

 
1. Navigate to /sitecore/content/Main/Website/Presentation/Rendering Variants/Image.
2. Insert a Variant Definition item and name it Banner Image only.
 
Banner Image only
 
3. Right-click on “Banner Image Only” node and add Field item named “Image.”
4. Now, add the Image Component from the SXA toolbar to your page and select the “Banner Image Only” variant from Variant dropdown menu on Image Component Toolbar.
5. You will see an Image Field thumbnail. Edit it to add your banner image.
6. After adding the image it should look like this.
 
Rendering Variant Dropdown
 

Banner with Link Variant

 
1. Add a new Variant Definition item and name it “Banner with Link.”
2. Add a Field type item and name it “Image.”
3. Add another for “TargetURL.”
4. Now drop the Image component on the page and Select “Banner with Link” variant from Variant dropdown.
5. Edit the fields to add Caption and Banner image.
 
TargetURL
 
6. After adding both Fields, it should look like below.
 
Banner Image with caption
 
To summarize, in the first post on Rendering Variants in SXA, we have looked at the basics of Rendering Variants. Subsequent posts will look at how to wrap a link around another Field Content and how to Render a Variant with a Custom Token.

]]>
https://blogs.perficient.com/2019/12/04/sitecore-experience-accelerator-sxa-rendering-variants-basic-usage/feed/ 0 269822