74

I am looking for a stand-alone, easy to use from C# code, template engine. I want to create an HTML and XML files with placeholders for data, and fill them with data from my code.

The engine needs to support loops (duplicating parts of the template form more that one object) and conditions (add parts of the template to the final HTML/XML only if some conditions are true). Can someone recommend a good option for me, and add a link to more-or-less such code sample, and some documentation about how to use the recommended component for my needs?

I also need to use loops to duplicate table rows, or even entire tables (in the HTML version) and complex elements (in the XML version).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • See also http://stackoverflow.com/questions/733378/whats-a-good-way-of-doing-string-templating-in-net – Simon Oct 05 '09 at 09:48
  • http://stackoverflow.com/questions/9176859/generate-html-file-at-runtime-and-send-as-email-attachment/9177106#9177106 – adt Apr 19 '12 at 14:16
  • A .NET Alternative to StringTemplate is https://github.com/beto-rodriguez/Templator, its simple and fast and you can install it form nuget `Install-Package Tor ` – bto.rdz Aug 12 '15 at 08:25
  • You can easily generate formatted text output from source template, input variables, and .NET classes with a few lines of code. The following TemplateEngine http://www.thedownloadplanet.com/reviews/template-engine-component-for-net/ is available for .NET, Silverlight and .NET Compact Framework. – brunoid Jun 29 '18 at 11:33

7 Answers7

24

I have used StringTemplate with good results. Some resources:

David Sykes
  • 48,469
  • 17
  • 71
  • 80
Fredrik Mörk
  • 155,851
  • 29
  • 291
  • 343
  • 1
    +1 - StringTemplate enforces a complete separation between view and model - which can be a big selling point or detractor depending on your needs. – Ian Robinson May 09 '11 at 21:46
20

What about T4, Text Template Transformation Toolkit? It should fit your requirements, and is built-in in Visual Studio.

Great T4 resources:

Oleg Sych's blog

T4 Editor

T4 Toolbox

Paolo Tedesco
  • 55,237
  • 33
  • 144
  • 193
  • 1
    One more thing that should be pointed out is that this is a templating engine with C# syntax. So there's no need to learn new templating syntax. – Robert Koritnik Nov 25 '10 at 21:40
19

There is a nice article how to use RazorView engine: How to create a localizable text template engine using RazorEngine

Malkov
  • 680
  • 1
  • 6
  • 8
11

SmartFormat is a pretty simple library that meets all your requirements. It is focused on composing "natural language" text, and is great for generating data from lists, or applying conditional logic.

The syntax is extremely similar to String.Format, and is very simple and easy to learn and use. Here's an example of the syntax from the documentation:

Smart.Format("{Name}'s friends: {Friends:{Name}|, |, and}", user)
// Result: "Scott's friends: Michael, Jim, Pam, and Dwight"

The library is open source and easily extensible, so you can also enhance it with additional features.

Scott Rippey
  • 15,614
  • 5
  • 70
  • 85
7

Have you looked at XSLT? You'll have to start with your source data format in XML, maybe by xmlserializing your data objects. You can do loops and if statements with ease!

Kathleen Dollard has a book on generating code via XSLT.

Personally, I'm a big fan of T4 (especially when generating C#), but you might find that since XML and HTML are your output types XSLT has you covered. Plus it's very cross-platform.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Rob Fonseca-Ensor
  • 15,510
  • 44
  • 57
  • 4
    The problem with XSLT is XSLT 1.x makes some simple tasks *painful* and XSLT 2.x is a myth (or, at least unavailable in my stack) :( –  Jun 13 '12 at 05:42
2

I have a templating engine built into my class library that looks and works similar to old-style ASP, or T4 for that matter.

You basically write C# code in <% %> blocks, and can thus do most things C# can do, with the limitation that the entire template file is being compiled to a single method. In other words, you can't define helper classes and such inside the template, but for helper methods you can do anonymous methods.

Example:

<%
    var firstname = "Bob";
    var count = 10;

    for (Int32 index = 0; index < count; index++)
    {
%>
<%= firstname %> x <%= index+1 %>/<%= count %>
<%
    }
%>

This will then be compiled to a C# class in another appdomain, and can be executed to return the string containing the produced text.

You can also pass an argument into the template, and also reference class libraries, which means you can pass custom data structures, or access data access layer or business logic code from your template.

If you want to look at it, the code is available in my class library from my Subversion repository or web page:

For the subversion repositories you need a username and password, both are "guest", without the quotes.

The code is in the LVK.Text.Templating project/assembly.

Also, let me know (see email on profile page, or leave comment) and I'll provide you with some more examples.

Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825
  • I don't quite understand why you have re-invented ASP.NET ... – Noon Silk Oct 05 '09 at 10:06
  • 5
    Considering I'm using it to generate code inside Visual Studio, amongst other things, I don't think it would be feasible to set up a full ASP.NET engine locally for that. I think you would balk at StringTemplate, as referred to by others to have a requirement that you would need a full IIS configuration set up for this. – Lasse V. Karlsen Oct 05 '09 at 12:22
  • @silky ASP.NET isn't just a templating language. – chakrit Dec 27 '09 at 09:00
  • I wish you hosted this on something more lasting, as I get 404's all around :) I would personally recommend BitBucket. In addition to providing free hosting that lasts, it also makes it that much easier for others to contribute tweaks by using Mercurial (SVN's design principles are a bit too ancient...) – Roman Starkov Jan 29 '10 at 00:03
  • I am working on it, replacing my references with something that lasts, but I will find a place which I control where I can script an upload, otherwise I'll have to release full snapshots of my source code, and it'll be a nightmare to maintain, but I agree, I need to find something better than the current. – Lasse V. Karlsen Jan 29 '10 at 11:03
  • Fixed the reference in a few posts, I'll see if I can find a way to go through them all, the repository is still up, just a slightly different url. As for "contributing tweaks by using Mercurial", I'm not going to change source control tool, and I'm not going to place my source on a public repository, so that's not going to happen. Subversion is perfect for my needs. – Lasse V. Karlsen Jan 29 '10 at 11:08
  • @LasseV.Karlsen SVN was perfect for me. Then I switched. Now I will never choose to go back. (Actually, looking back, SVN was *never* a really good fit for code... branches? merging? uhg :-) –  Jun 13 '12 at 06:36
1

You may need this .NET Template Engine.

Template Code:

$Book.StaticId$

ID: $bk.BookId$ - Author: $bk.Author.Name$

Length of the author's Name: $bk.Author.Name.Length$

C# Code:

class Author
   {
       public string Name
       {
           get
           {
               return "John Borders";
           }
       }
   }
   class Book
   {
       public static string StaticId
       {
           get
           {
               return "AABB";
           }
       }
       public int BookId
       {
           get
           {
               return 100;
           }
       }
       public Author Author
       {
           get
           {
               return new Author();
           }
       }
   }
   public class PropertySample1
   {
       [STAThread]
       static void Main()
       {
           TemplateEngine dt = new TemplateEngine();
           dt.LoadFromFile("Template.tpl");
           Book book = new Book();
           dt.SetValue("bk", book);
           dt.UsingNamespace("CSharp,Demo");
           string output = dt.Run();
           Console.WriteLine(output);
       }
   }

Output is:

AABB

ID: 100 - Author: John Borders

12
  • 9
    I can't imagine why anyone would pay money for that as opposed to just using T4 templates. Are these better than T4 templates in some way? – John Saunders May 09 '10 at 23:35
  • 1
    T4 is compiled templates, therefore the user cant create his own templates without having a .NET compiler. but still there are many opensource alternatives – Tomer W Oct 19 '17 at 05:42