39

By basic T4 template, I mean not using T4 Toolkit or any of the add-ins.

My T4 is getting a little complicated, but I'd like to keep in self-contained for now. Is there a way have functions in your T4 template, without referencing external assemblies?

Patrick Karcher
  • 22,995
  • 5
  • 52
  • 66

1 Answers1

62

You mean like this:

<#+
    public List<string> Dostuff()
    {
        List<string> result = new List<string>(); 

        // ...

        return result;
    }
#>

Here's a complete example: Reading a Xml File in T4 Templates

Oleg Sych's T4Toolbox is a good resource.

BurnsBA
  • 4,347
  • 27
  • 39
Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541
  • 2
    "<#+ #>", excellent, that's what I'm after. Do you know, can you define types in that *<#+* code block? – Patrick Karcher Feb 04 '10 at 16:08
  • 7
    Note that these class feature control blocks have to in the end of your t4-file, otherwise you'll get syntax errors. – Alex Sep 23 '16 at 06:49
  • But this does not allow you to render stuff from inside that function, as you would in a PHP function, right? Is this PHP-like behavior possible (e.g. switch between rendering-mode and code-mode within the function definition)? I think it would be handy to allow this somehow for repetitive rendering tasks... – user2173353 Oct 16 '17 at 08:33
  • Microsoft link is broken. – Sinatr Jul 13 '20 at 11:57