【问题标题】:Text templates for string generation at run-time (like Razor or T4)运行时生成字符串的文本模板(如 Razor 或 T4)
【发布时间】:2011-12-04 21:59:39
【问题描述】:

网上有没有可以用来从模板生成字符串的工具,我正在寻找类似于Razor的东西。

字符串应该能够在运行时生成,并且不依赖于 Visual Studio(如 T4)。该框架应该可以在 Silverlight 中运行。

RazorEngine 是一个满足要求但在 Silverlight 中不起作用的框架。

提前致谢。

【问题讨论】:

  • 当您说“仅适用于 .NET”时,您的意思是它不适用于 Silverlight?
  • @FuleSnabel 是的,你说得对,我在这个问题上更正了这个问题

标签: c# silverlight razor t4


【解决方案1】:

希望我理解您的要求,但我认为您也可以让 T4 在 SL 中工作。可以要求 T4 生成有时称为运行时模板的内容。我已经定义了我的模板(非常简单)并将其添加到我的 Silverlight 项目中。

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

通常它会产生这样的输出:

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

但在这种情况下,我喜欢生成生成该输出的代码,即运行时模板。为此,我将自定义工具切换为:TextTemplatingFilePreprocessor

现在模板生成生成该输出的代码。如果您不使用 hostspecific=true,则不会获得 Visual Studio 依赖项。通过使用成员变量扩展分部类并从模板文件中引用它们,您可以在运行时修改模板上的行为。

Silverlight 中的问题是silverlight 缺少类:System.CodeDom.Compiler.CompilerError 和 System.CodeDom.Compiler.CompilerErrorCollection。

我为此创建了自己的类来解决这个问题(仅出于此目的):

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

    public class CompilerErrorCollection : List<CompilerError>
    {

    }

}

现在我的模板编译好了,我就这样从我的 Silverlight 应用程序中生成输出:

var runtimeTemplate = new MyRuntimeTemplate();
string output = runtimeTemplate.TransformText();

【讨论】:

    猜你喜欢
    • 2013-02-26
    • 1970-01-01
    • 1970-01-01
    • 2011-11-20
    • 2011-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-04
    相关资源
    最近更新 更多