Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Text templates for string generation at run-time (like Razor or T4)

Is there any tool on the web that can be used to generate strings from a template, i'm looking for something similar to Razor.

The strings should be able to be generated at run time, and don't depend on Visual Studio (like T4). And the framework should work in Silverlight.

RazorEngine is a framework that meets the requeriments but doesn't work in Silverlight.

Thanks in advance.

like image 765
Ariel Avatar asked Oct 10 '11 23:10

Ariel


1 Answers

Hopefully I understood what you asked for but I would argue that you can make T4 work in SL as well. T4 can be asked to generate what is sometimes called runtime templates. I have defined my template (very simple) and added it to my Silverlight project.

<#
    for (var iter = 0; iter < 10; ++iter)
    {
#>
    This is just a test: #<#=iter#>
<#
    }
#>

Normally it would generate an output like this:

This is just a test: #0
This is just a test: #1
This is just a test: #2
This is just a test: #3
This is just a test: #4
This is just a test: #5
This is just a test: #6
This is just a test: #7
This is just a test: #8
This is just a test: #9

But in this case I like to generate the code that generates that output ie a runtime template. In order to do that I switch the custom tool to: TextTemplatingFilePreprocessor

Now the template generates the code that generates that output. If you stay clear of hostspecific=true you don't get Visual Studio dependencies. By extending the partial class with member variables and referencing them from the template file you can modify the behavior on the template in runtime.

The problem in Silverlight is that silverlight lacks the classes: System.CodeDom.Compiler.CompilerError and System.CodeDom.Compiler.CompilerErrorCollection.

I worked around that by creating my own classes for that (just for this purpose):

namespace System.CodeDom.Compiler
{
    public class CompilerError
    {
        public string ErrorText;
        public bool IsWarning;
    }

    public class CompilerErrorCollection : List<CompilerError>
    {

    }

}

Now my template compiles and I just it like this from my Silverlight app to produce the output:

var runtimeTemplate = new MyRuntimeTemplate();
string output = runtimeTemplate.TransformText();
like image 155
Just another metaprogrammer Avatar answered Oct 12 '22 18:10

Just another metaprogrammer