0

I need to build a web templating engine in Python. I know there are a few out there, but I need to write my own. I need to take care of two things:

  1. String substitutions
  2. For loop constructs

Any help on this matter will be highly appreciated. I have thought about it, but don't know how to proceed.

Also, I am new to SO, so pardon my mistakes.

Varun Shah
  • 53
  • 1
  • 7
  • 2
    Why not take a look at existing source for inspiration, like [jinja2](https://github.com/mitsuhiko/jinja2/tree/master/jinja2)? – miku Nov 16 '13 at 11:22
  • On the same lines, let me suggest [Django](https://github.com/django/django) – shad0w_wa1k3r Nov 16 '13 at 11:34
  • I think its way too complicated. I want to implement much simpler stuff. But I'll have a look at it anyway. Thanks! – Varun Shah Nov 16 '13 at 11:37
  • `need` # This is only ever true if you know what you're doing and none of the existing ones do what you need to do, or somebody else is demanding you write one yourself. Having done this myself at least once, I can say its a bad idea, and you should use an existing solution **IF AT ALL POSSIBLE**, because otherwise you'll simply be repeating all their mistakes. – Kent Fredric Nov 16 '13 at 22:15
  • Well, its a homework assignment and I need to write my own. I just need some intuition/direction/guidance as to how to go about it. I don't mind using an existing logic either, but I couldn't find anything I can refer to. – Varun Shah Nov 17 '13 at 01:59

1 Answers1

1

Well, if you wish for string substitutions, then you can try the following:

>>> "{0}".format("Hello")
'Hello'
>>> "{name}".format(name="Hello")
'Hello'

If you wish to make for loop constructs, it will be a bit more difficult:

>>> names = ['Joe', 'Bob', 'Stanley', 'Ahmed', 'Inbar', 'Hossain']
>>> var = "".join("{number} -> {name}\n".format(name=name, number=n) for n, name in enumerate(names))
>>> var
'0 -> Joe\n1 -> Bob\n2 -> Stanley\n3 -> Ahmed\n4 -> Inbar\n5 -> Hossain\n'
>>> print var
0 -> Joe
1 -> Bob
2 -> Stanley
3 -> Ahmed
4 -> Inbar
5 -> Hossain

The above is an example of what can be done, of course, you can do things like at li tags using this kind of formatting:

var = "".join("<li>{name}</li>\n".format(name=name, number=n) for n, name in enumerate(names))

Would produce:

<li>Joe</li>
<li>Bob</li>
<li>Stanley</li>
<li>Ahmed</li>
<li>Inbar</li>
<li>Hossain</li>
Games Brainiac
  • 80,178
  • 33
  • 141
  • 199