Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could we have in python web page generated as in php?

Tags:

python

web

Can we write in python language (or maybe exist such a web framework), that we could write Python and html tags as in PHP language.

Could we have such a python file structure:

some_python_file.py:

<html>
<head>
     <title>Lol</title>
<head>
<body>
    My PyWeb Slang
</body>
</html>

<!-- this part should be python -->
<?py
    from Eternity import Kiss

    love = Kiss.Forever()
    print "%s" % love
?>

sorry i'm writting with caps: DISAMBIGUATION:

You can see, that template use in each line {% goodies %} or <%= goodies %>

{% extends "layout.html" %}
{% block body %}
  <ul>
  {% for user in users %}
    <li><a href="{{ user.url }}">{{ user.username }}</a></li>
  {% endfor %}
  </ul>
{% endblock %}

But in PHP:

<div>Good Morning, Sun!</div>
<?php

     echo "Happy!";
     echo "Hi, WaterLand!";

?>

If Python could do it that way, it should be like:

<div>Good Morning, Sun!</div>

<?py

     print "%s" % "Happy!"
     print "%s" % "Hi, WaterLand!";

?>

Got the ideia, or I need to be more explicit?

Thank You. :)

Hm, if so:

Could we write with mod_python something like (extending [morphyn] example from below):

<html>
<%
    greet = 'Hello Wee!'
    answer = 'Hello Bee!'
%>
<h1><%= greet %></h1>
<h2><%= answer %></h2>
</html>

There you can see more than 2'u lines into <% ... %> Could we?


1 Answers

This is not exactly what you're asking for, but the proper way to do this is to use a template engine. Take a look at Jinja2. Django also provides its own template engine.

Update:

By default, Python cannot be embedded in HTML pages. There is however at least one way of doing it. mod_python, a module for Apache2, offers the kind of feature you want with PSP (Python Server Pages).

<html>
<%
    greet = 'Hello'
%>
<h1><%= greet %></h1>
</html>

Keep in mind that mixing logic and presentation is generally not a good idea. The proper way to go is still to use a template engine, as stated in my original answer. You may have very good reasons to do what you want to do, but probably not.

like image 168
Martin Maillard Avatar answered Nov 24 '25 07:11

Martin Maillard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!