【发布时间】:2008-12-28 18:40:07
【问题描述】:
我正在寻找一个模拟 Ruby 的 ERB 库的部分功能的库。即用文本替换 之间的变量。我不需要 ERB 提供的代码执行部分,但如果你知道有这方面的东西,我会非常感激。
【问题讨论】:
我正在寻找一个模拟 Ruby 的 ERB 库的部分功能的库。即用文本替换 之间的变量。我不需要 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<string, object> valueMap = new Dictionary<string, object>();
List<string> matches = new List<string>();
// 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 (i.e. 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<string, object> pair in valueMap)
{
// Replace the tag with the corresponding value.
result = result.Replace(pair.Key, pair.Value.ToString());
}
return result;
}
private List<string> GetMatches(string subjectString)
{
try
{
List<string> matches = new List<string>();
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<string>();
}
}
public string GetTagValue(string tag)
{
string result = tag.Replace("<%=", string.Empty);
result = result.Replace("%>", string.Empty);
return result;
}
}
【讨论】:
看看TemplateMachine,我没测试过,不过好像有点像ERB。
【讨论】:
以前有帮助的链接不再可用。我已经留下了标题,所以你可以用谷歌搜索它们。
还要寻找“C# Razor”(这是 MS 与 MVC 一起使用的模板引擎)
还有更多。
Visual Studio 附带 T4,这是一个模板引擎(即 vs 2008,2005 需要免费插件)
免费 T4 编辑器 - 死链接
T4 Screen Cast - DEAD LINK
有一个开源项目叫Nvolicity,被Castle Project接手
Nvolictiy Castle 项目升级 - 死链接
HTH 骨头
【讨论】:
我刚刚发布了一个非常简单的库,用于替代有点像 ERB。
您不能在<%%> 大括号中进行计算,您只能使用这些大括号:<%= key_value %>。 key_value 将是作为替代参数传递的 Hashtable 的键,大括号将替换为 Hashtable 中的值。就是这样。
https://github.com/Joern/C-Sharp-Substituting
你的,
乔恩
【讨论】: