ERB喜欢C#的库

我希望找到一个模仿Ruby的ERB库的部分function的librray。 即在之间替换变量的文本。 我不需要ERB提供的代码执行部分,但如果你知道有这样的东西,我会非常感激。

看看TemplateMachine ,我还没有测试过,但它似乎有点像ERB一样。

我修改了一个我以前用来测试一些东西的类。 它甚至没有ERB那么好,但它完成了替换文本的工作。 它只适用于属性,因此您可能想要修复它。

用法:

Substitutioner sub = new Substitutioner( "Hello world <%=Wow%>! My name is <%=Name%>"); MyClass myClass = new MyClass(); myClass.Wow = 42; myClass.Name = "Patrik"; string result = sub.GetResults(myClass); 

码:

 public class Substitutioner { private string Template { get; set; } public Substitutioner(string template) { this.Template = template; } public string GetResults(object obj) { // Create the value map and the match list. Dictionary valueMap = new Dictionary(); List matches = new List(); // Get all matches. matches = this.GetMatches(this.Template); // Iterate through all the matches. foreach (string match in matches) { if (valueMap.ContainsKey(match)) continue; // Get the tag's value (ie Test for <%=Test%>. string value = this.GetTagValue(match); // Get the corresponding property in the provided object. PropertyInfo property = obj.GetType().GetProperty(value); if (property == null) continue; // Get the property value. object propertyValue = property.GetValue(obj, null); // Add the match and the property value to the value map. valueMap.Add(match, propertyValue); } // Iterate through all values in the value map. string result = this.Template; foreach (KeyValuePair pair in valueMap) { // Replace the tag with the corresponding value. result = result.Replace(pair.Key, pair.Value.ToString()); } return result; } private List GetMatches(string subjectString) { try { List matches = new List(); Regex regexObj = new Regex("<%=(.*?)%>"); Match match = regexObj.Match(subjectString); while (match.Success) { if (!matches.Contains(match.Value)) matches.Add(match.Value); match = match.NextMatch(); } return matches; } catch (ArgumentException) { return new List(); } } public string GetTagValue(string tag) { string result = tag.Replace("<%=", string.Empty); result = result.Replace("%>", string.Empty); return result; } } 

更新了post

提供帮助的链接不再可用。 我已经离开了标题,所以你可以谷歌他们。

也寻找“C#Razor”(这是MS与MVC一起使用的模板引擎)


那里还有几个。

Visual Studio附带T4,这是一个模板引擎(对比2008,2005需要免费添加)

免费T4编辑器 – DEAD LINK

T4 Screen Cast- DEAD LINK

有一个名为Nvolicity的开放式项目,由Castle Project接管

Nvolictiy Castle项目升级 – DEAD LINK

HTH Bones

我刚刚发布了一个非常简单的库,用于替换ERB。

您无法在<%%>大括号中进行评估,您只能使用这些大括号: <%= key_value %>key_value将是您作为替换参数传递的Hashtable的键,并且大括号被Hashtable中的值替换。 就这样。

https://github.com/Joern/C-Sharp-Substituting

此致,

Joern