The project I’m currently working on requires me to use the Python’s built in HTTP server and I need to build dynamic HTML pages on my own. The %REPLACE_ME% syntax in HTML files has recently got too annoying and I’d love to replace it with in-place code as it’s done in PHP. Is there any good solution to parsing a string with (or any other similar syntax) and evaling the code inside?
Edit:
Jon Clements pointed me out that I forgot to explain why would I need the in-place code. There are two reasons – first is that I’m used to such approach, the latter being that I’d like to use some loops and don’t want to end myself constructing half of the HTML code for e.g. tables in the model file. The stdlib requirement is because I’d like to keep dependencies as little as possible. I could allow for some really really slim library for that though.
As per the last comment I will try and outline some options:
Built in to python the best options is the
stringmodule.As stated in the comments the documentation is here: 7.1. string
There are a lot of third party templating systems which are incredibly powerful. I am not a big PHP user but you would class these similar to Smarty etc…
Django Template
There is also a great open source book related to using them Django Book: Chapter 4 – Templating
I have never used these outside of Django but I know there is a few frameworks which let you use them. I am not to sure how much work this would be to integrate it with another system but it definitely can be done.
Mako Templates
This is another good templating system which is really powerful. This is used by some big frameworks like Pylons.
Jinja2
This is also a good templating system.
There are a few other discussions around SO about templating systems: What is the fastest template system for Python?. This is just an example but there is a much bigger list of template systems there.