我认为这有助于讨论,因为它帮助我在使Python变得非常适合网络方面。
Metalfan,我看到你在聊天时询问:
Are there any libraries which makes Python work like PHP. I mean embed
into HTML something like
你问一个模板库来构建html,css,javascript,sql或其他任何东西。我已经搜索了一个工具来做到这一点,并找到了Cog,Cheetah以及谷歌抛出的大部分内容。我受到Django的启发,它给模板处理对象和基本上整个语言的访问权限,而不仅仅是进行宏扩展。
Web2py有一个模块可以做到这一点,我发现它很容易修改或使用独立。我不记得我是否对我正在使用的原版so I've uploaded the version进行了任何修改,因此它应该可以开箱即用。
要从模板生成代码,请包含模板模块,并使用模板(字符串)和上下文(包含本地环境的dict)调用render函数。喜欢这个:
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)然后模板看起来像这样:
Hello {{= username }}
{{ 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): }}
{{ pass }}
{{ pass }}
{{ # imported function }}
100 chars of google html get:
{{ =lam()[:100] }}
{{ # you can access the whole language with this }}
{{ =f()}}....它给出了这个输出:
Hello mortn
this isn't printed unless if-statement matches
- 1
- 2
- 3
100 chars of google html get:
<!doctype html><html itemscope="itemscope"itemtype="http://schema.org/WebPage"><head><meta itemprop
you can do whatever你可以看到它与白色间距有点混淆,我已经缩短了输出,因为每个{{block生成一个换行符。它可以在template.py模块中编辑,因为它具有符合PEP8的非常易读的代码。
TL; DR:
以下是单个文件中示例代码的链接:
http://pastie.org/4776120
和template.py模块:http://pastie.org/4775988