Python template engine

前端 未结 3 548
旧时难觅i
旧时难觅i 2020-12-30 14:39

Could it be possible if somebody could help me get started in writing a python template engine? I\'m new to python and as I learn the language I\'ve managed to write a littl

3条回答
  •  星月不相逢
    2020-12-30 15:20

    Well, when I decide to play around like you did, TDD is always a good way to go.

    so, why not give it a go?

    for example, create a file called jturo_template.py and write:

    import re
    import unittest
    
    class JTuroTemplate(object):
        u"""JTuro's template engine core class"""
        variable_regex = r'\$\{((.*)(%s)([^}]*))*\}'
        def __init__(self, string):
            self.string = string
    
        def __repr__(self):
            pieces = self.string.split()
            if len(pieces) > 3:
                head = "%s ..." % " ".join(pieces[:3])
            else:
                head = " ".join(pieces)
    
            return u'' % (head)
    
        def render(self, context):
            new = unicode(self.string)
    
            for key, value in context.items():
                variable_name = re.escape(key)
                regex = re.compile(self.variable_regex % variable_name)
    
                for match in regex.findall(new):
                    if match[0]:
                        replacement = match[0].replace(key, repr(value))
                        new = new.replace('${%s}' % match[0], unicode(eval(replacement)))
    
            return new
    
    class TestJTuroTemplate(unittest.TestCase):
        def test_repr(self):
            "a instance will be nicely represented"
            jt = JTuroTemplate('my template')
            self.assertEquals(repr(jt), '')
    
        def test_repr_truncated(self):
            "the python representation is truncated after 3 words"
    
            jt = JTuroTemplate('such a long string template')
            self.assertEquals(repr(jt), '')
    
        def test_solves_simple_variables(self):
            "it solves simple variables"
    
            jt = JTuroTemplate('my variable is ${var} == 4')
            self.assertEquals(jt.render({'var': '4'}), 'my variable is 4 == 4')
    
        def test_solves_variables_with_python_code(self):
            "it solves variables with python code"
    
            jt = JTuroTemplate('my variable is ${var + var} == 44')
            self.assertEquals(jt.render({'var': '4'}), 'my variable is 44 == 44')
    
    if __name__ == '__main__':
        unittest.main()
    

    Sorry for the long post, but I think you can try this workflow:

    1. write test that fail
    2. run and watch it fail
    3. write code to make the test pass
    4. run again and watch it pass

提交回复
热议问题