Сайт Игоря Кононученко   Статьи

Template из Prototype.js на C# 3.0

20 января 2008

Видели ли вы когда либо такой синтаксис в джаваскрипте:

1
2
3
4
5
6
7
8
9
// the template (our formatting expression)
var myTemplate = new Template('The TV show #{title} was created by #{author}.');

// our data to be formatted by the template
var show = {title: 'The Simpsons', author: 'Matt Groening', network: 'FOX' };

// let's format our data
myTemplate.evaluate(show);
// -> The TV show The Simpsons was created by Matt Groening.

Думаю, те кто знаком с библиотекой Prototype.js , определенно да. Этот функционал реализован в классе Template, у которого есть всего один метод, evaluate. Он делает замену в текстовом шаблоне, используя поступающий на вход обьект с данными.

А теперь более вскусная часть. А как думаете, можно ли такое сделать в C# 3.0? Конечно да. Для начала пишем тест.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
[TestMethod()]
        public void EvalTest()
        {
            string template = "some string #{templateParam1} and #{someOtherParam}";
            Template target = new Template(template);      
            

            object o =new { templateParam1 = "12", someOtherParam = "other string" };
            string actual = target.Evaluate(o);
            string expected = "some string 12 and other string";
            Assert.AreEqual(expected, actual);
        }

Потом немного рефлекшна и у нас готов настоящий прототайповский Template на C# 3.0.

 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
public class Template
    {
       
        readonly string  _template;
    
        private  Hashtable GetPropertyHash(object properties)
        {

            Hashtable values = null;
            if (properties != null)
            {
                values = new Hashtable();
                PropertyDescriptorCollection props = TypeDescriptor.GetProperties(properties);
                foreach (PropertyDescriptor prop in props)
                {
                    values.Add(prop.Name, prop.GetValue(properties));
                }
            }

            return values;
        }

        public Template(string template)
        {
            _template = template;
        }
        public string Evaluate(object o)
        {
            Hashtable table = GetPropertyHash(o);
            string s = _template;
            foreach (DictionaryEntry v in table)
            {
                s = s.Replace("#{"+v.Key+"}",v.Value.ToString());
            }
            return s;
        }

    }

Пользуйтесь наздоровье:)

Linq to SQL и DDD
Continuous Integration в django-проекте
Ctrl
Python yield — простым языком
Динамические запросы (фильтры) в django