Skip to main content
 首页 » 编程设计

Python 在 HTML 中替代 PHP

2025年05月04日26Leo_wl

是否可以像使用 PHP 一样使用 Python 进行 Web 开发?

换句话说,我可以在我的 HTML 中添加一些 python 代码,这些代码在服务器上运行并可能添加到 HTML 中吗?

例如一些PHP代码:

<p>Cheese:</p>  
<ul> 
<?php 
    $cheeses = ['brie', 'cheddar', 'death star']; 
    foreach ($cheeses as $c){ 
        echo "<li>".$c."</li>"; 
    } 
?> 
</ul> 
<p>No more cheese :(</p> 

使用 python 可以是:

<p>Cheese:</p>  
<ul> 
<?py 
    cheeses = ['brie', 'cheddar', 'death star'] 
    for c in cheeses: 
        print ("<li>" + c + "</li>") 
?> 
</ul> 
<p>No more cheese :(</p> 

请您参考如下方法:

Python 本身并不是一种 Web 开发语言。但是,您可以将它与某些 Web 框架(如 Django、Flask 等)一起使用,以便使用模板标签 和过滤器 在模板中执行操作。对于 Django,请参阅 Django's built-in tags有关可用操作的完整列表的文档。

因此,您在 Django 模板中的等效 for 循环将如下所示:

{% for c in cheeses %} 
    <li> {{ c }} </li> 
{% endfor %} 

在呈现模板时,您必须在其中传递带有上下文对象的 cheeses 列表。