forked from xuxiaowei007/FoxOne
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStringTemplate.cs
46 lines (41 loc) · 1.31 KB
/
StringTemplate.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace FoxOne.Core
{
public class StringTemplate
{
public static readonly Regex Pattern = new Regex(@"\$(?<Variable>.+?)\$", RegexOptions.Compiled);
public string ItemTemplate { get; set; }
private IDictionary<string,object> Data;
public StringTemplate(string itemTemplate)
{
ItemTemplate = itemTemplate;
}
public void SetAttribute(object value)
{
Data = value.ToDictionary();
}
private object Resolve(string name)
{
if (Data.IsNullOrEmpty() || !Data.Keys.Contains(name,StringComparer.OrdinalIgnoreCase)) return string.Empty;
return Data[name];
}
public override string ToString()
{
StringBuilder builder = new StringBuilder();
var arr = Pattern.Split(ItemTemplate);
for (int i = 0; i < arr.Length; i++)
{
builder.Append(arr[i++]);
if (i < arr.Length)
{
builder.Append(Resolve(arr[i]));
}
}
return builder.ToString();
}
}
}