C# Typewriter - How to reuse chunks of the template

363 Views Asked by At

I've been trying to figure out is there is a way to reuse parts of the template so that I do not have repeat the same stuff all over the place. Here is the template:

$Classes(MyProject.Model.*)[
$NestedEnums[
export enum $Parent_$Name { $Values[$Name = $Value][,] }]

export class $Name {
    $Properties[
    public $Name: $Type = $Type[$Default];]
}

$NestedClasses[
$NestedEnums[
export enum $Parent_$Name { $Values[$Name = $Value][,] }]

export class $Name {
    $Properties[
    public $Name: $Type = $Type[$Default];]
}
]
]

EDIT: So, I was able to figure out how to include different Namespaces, you can just use a lambda expression to accomplish it like so:

$Classes(c => c.Namespace == "MyProject.Model" || c.Namespace == "MyProject.Comms")

So, all I need to figure out now is if it possible to reuse parts of the template. This section in the $Classes part:

$NestedEnums[
export enum $Parent_$Name { $Values[$Name = $Value][,] }]

export class $Name {
    $Properties[
    public $Name: $Type = $Type[$Default];]
}

Is exactly the same as the one inside the $NestedClasses part, and it would be great if I can just reuse it somehow! Any help would be greatly appreciated.

1

There are 1 best solutions below

0
RocketMan On

If there is functionality that you want to reuse in multiple places in your template, I would place it in its own C# function (outside the $Classes part of the template, but within the ${} outermost brackets in the .tst file) and then call that function wherever you need it in your template. This function would take in an Enumeration and return a string.

Take a look at how the rendering of Knockout Observables is handled by the "KnockoutInitializer" function in this example from the Typewriter website: http://frhagn.github.io/Typewriter/pages/examples.html. There is also some documentation under the "Custom methods" heading here: http://frhagn.github.io/Typewriter/pages/getting-started.html

Hope this helps!