Ruby の ERB ライブラリの機能の一部をエミュレートするライブラリを探しています。つまり、<% と %> の間の変数をテキストに置き換えます。ERB が提供するコード実行部分は必要ありませんが、これを備えたものを知っていれば、非常に感謝しています。
4 に答える
少し前にいくつかのことをテストするために使用したクラスを変更しました。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 エディター - DEAD LINK
T4 スクリーン キャスト - DEAD LINK
Castle Projectに引き継がれたNvolicityというオープンソースプロジェクトがあります
Nvolictiy Castle プロジェクトのアップグレード - DEAD LINK
HTHボーンズ
ERB に少し似たものを置き換えるための非常に単純なライブラリをリリースしました。
中かっこで評価することはできません。<%%>
次の中かっこのみを使用できます: <%= key_value %>
. key_value
は、置換引数として渡す Hashtable のキーになり、中かっこは Hashtable の値に置き換えられます。それで全部です。
https://github.com/Joern/C-Sharp-Substituting
あなたの、
ヨルン