<p>我认为这有助于讨论,因为它有助于我使Python成为web上的佼佼者。</p>
<p>Metalfan,我看到你在聊天中问:</p>
<blockquote>
<p>Are there any libraries which makes Python work like PHP. I mean embed
into HTML something like </p>
</blockquote>
<p>您询问的是一个模板库,用于构建html、css、javascript、sql或其他任何东西。我已经找了一个工具来做这件事,找到了<a href="http://www.python.org/about/success/cog/" rel="nofollow">Cog</a>,<a href="http://www.cheetahtemplate.org/" rel="nofollow">Cheetah</a>以及谷歌向你抛出的其他大部分东西。我的灵感来自于我在Django的工作,它让模板处理能够访问对象和基本上整个语言,而不仅仅是做宏扩展。
<a href="http://www.web2py.com/" rel="nofollow">Web2py</a>有一个这样做的模块,我发现修改或使用独立的模块非常容易。我不记得我是否对原来的<a href="http://pastie.org/4775988" rel="nofollow">so I've uploaded the version</a>做了任何修改,所以应该是开箱即用的。</p>
<p>要从模板生成代码,可以包含<strong>模板</strong>模块,并使用模板(字符串)和上下文(包含本地环境的dict)调用render函数。像这样:</p>
<pre><code>from template import render
import urllib2
environment = dict(
elements=[1, 2, 3],
username="mortn",
session_id="xyz",
lam=lambda x=0: urllib2.urlopen("http://google.com").read(),
f=f,
)
print render(content=html_template, context=environment)
</code></pre>
<p>模板将如下所示:</p>
<pre><code><html>
<h1>Hello {{= username }}</h1><br/>
{{ if session_id=="xyz": }}
{{ # indentation doesn't matter.. }}
this isn't printed unless if-statement matches
{{ else: }}
instead this would be shown
{{ pass # each if/for/while statements (that would
{{ # "indent your code"), must end with pass }}
{{ for e in elements: }} - {{=e}}
{{ pass }}
{{ # demo of looping }}
{{ if 1: }}
{{ for i in xrange(10): }}<br/>{{ pass }}
{{ pass }}
{{ # imported function }}
100 chars of google html get:
{{ =lam()[:100] }}
{{ # you can access the whole language with this }}
{{ =f()}}
</code></pre>
<p>。。。。它给出了这个输出:</p>
<pre><code><html>
<h1>Hello mortn</h1><br/>
this isn't printed unless if-statement matches
- 1
- 2
- 3
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
100 chars of google html get:
&lt;!doctype html&gt;&lt;html itemscope=&quot;itemscope&quot;itemtype=&quot;http://schema.org/WebPage&quot;&gt;&lt;head&gt;&lt;meta itemprop
you can do whatever
</code></pre>
<p>你会看到,它与白色间距有些混淆,我已经缩短了输出,因为每个{{块生成一个换行符。它可以在template.py模块中编辑,因为它具有非常可读的代码,符合PEP8。</p>
<p><strong>TL;博士:
下面是单个文件中示例代码的链接:
<a href="http://pastie.org/4776120" rel="nofollow">http://pastie.org/4776120</a>
以及template.py模块:<a href="http://pastie.org/4775988" rel="nofollow">http://pastie.org/4775988</a></strong></p>