Template code generator

Reading time ~1 minute

Are you using Habitat approach when implementing projects and have PowerShell installed on your instance? I’ve got a great time saver. Read more to see how SPE can generate code for you.

Introduction

If you are implementing your solution using Habitat approach you probably know how item templates are reflected in the code?

Here is an example:

DatasourceConfiguration is a template with two fields:

To easily access those fields in code, template is mapped into following structure:

1
2
3
4
5
6
7
8
9
10
public struct DatasourceConfiguration
{
  public static ID ID = new ID("{C82DC5FF-09EF-4403-96D3-3CAF377B8C5B}");

  public struct Fields
  {
    public static readonly ID DatasourceLocation = new ID("{5FE1CC43-F86C-459C-A379-CD75950D85AF}");
    public static readonly ID DatasourceTemplate = new ID("{498DD5B6-7DAE-44A7-9213-1D32596AD14F}");
  }
}

source: Templates.cs

Templates code generator

Templates.cs creation process is pretty obvious and what is more important very easy to automate. Because of that I created small PowerShell script which will do the magic for you.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
$templateItem = Get-Item .

function Get-FieldText($field){
    Write-Host "`t`tpublic static readonly ID $(Get-ValidName $field.Name) = new ID(`"$($field.ID)`");"
}

function Get-ValidName($name){
    $name.Replace(' ','')
}

$fields = Get-ChildItem -Path $templateItem.Paths.Path -Recurse | ?{ $_.TemplateName -eq "Template field"}

Write-Host "public struct $(Get-ValidName $templateItem.DisplayName)"
Write-Host "{"
    Write-Host "`tpublic static ID ID = ID.Parse(`"$($templateItem.ID)`");"
    Write-Host "`tpublic struct Fields"
    Write-Host "`t{"
    $fields | %{ Get-FieldText $_ }
    Write-Host "`t}"
Write-Host "}"

Show-Result -Text -Width 900
Close-Window

Here is a quick demo how you can use it:

If you like how I integrated it with Context Menu in Content Editor you can download SPE module here: Template code generator-1.0.zip

With power of rules engine I was able to show my script in Context Menu when you are on Template item only so don’t worry about unnecessary entries in scripts section.

Summary

This small script will save your time and make your work less error prone.

You don’t have to worry about wrongly copied ID or misspelled name.

Enjoy!

Asset Optimizer configuration

Explanation of different configuration options of SXA Asset Optimizer Continue reading

Items as resources and Unicorn

Published on November 21, 2021

Sitecore Extensions version 3.4 released

Published on November 07, 2020