phppythonhtmlpreprocessorweb-frameworks

Python web pages, PHP-style


I have used Python and PHP a lot, but just out of curiosity, is there a version of Python that uses a similar paradigm to PHP for dynamic creation of html pages, i.e. like this:

<html>
<body>

<?py                        # similar to <?php ... ?>
for i in range(10):
    print '<div>Hello%i</div>' % i
?>

</body>
</html>

?


Note 1: I'm not speaking about Django, Flask, Bottle, Twisted, etc. that don't use such syntax.

Note 2: The suggested code would be like this in PHP:

<html>
<body>

<?php 
for ($i = 0; $i < 10; $i++)
{ 
    echo '<div>Hello' . $i . '</div>'; 
}
?>

</body>
</html>

Solution

  • Is there a version of Python that uses a similar paradigm to PHP for dynamic creation of html pages

    No, Python cannot be embedded in HTML like the way you want. The idea is to separate the view (HTML) from the code (Python).

    Have a look at how template engine works, they can allow fairly complex amount of Python code.

    Example with Jinja:

        <ul>
            {% for user in users %}
                <li><a href="{{ user.url }}">{{ user.username }}</a></li>
            {% endfor %}
        </ul>
    

    Other solutions closer to what you want will convert the html to a Python script that will produce the fully interpreted HTML. It's a bit of an overkill...