Python中的CL-WHO:聪明还是愚蠢?
我不知道这是聪明还是愚蠢。我喜欢CL-WHO,我也喜欢Python,所以我一直在设法将两者融合在一起。我想说的是:Python中的CL-WHO:聪明还是愚蠢?,python,html,lisp,Python,Html,Lisp,我不知道这是聪明还是愚蠢。我喜欢CL-WHO,我也喜欢Python,所以我一直在设法将两者融合在一起。我想说的是: tag("html", lst( tag("head"), tag("body", lst( tag("h1", "This is the headline"), tag("p", "This is the article"), tag("p", ta
tag("html",
lst(
tag("head"),
tag("body",
lst(
tag("h1", "This is the headline"),
tag("p", "This is the article"),
tag("p",
tag("a", "Click here for more", ["href", "http://nowhere.com"]))))))
并对此进行评估:
<html>
<head>
</head>
<body>
<h1>This is the headline</h1>
<p>This is the article</p>
<p>
<a href="http://nowhere.com">Click here for more</a>
</p>
</body>
</html>
为了方便条件代码的生成,您需要一个if语句,它是一个计算结果为两个结果之一的函数,如在Lisp中,这样您就可以嵌套它。一个命令式的流控制样式如果不行的话
def fif(cond, a, b):
if cond:
return a
else:
return b
维奥伊拉。现在,您可以生成如下示例页面:
def gen(x):
"""Sample function demonstratine conditional HTML generation. Looks just like CL-WHO!"""
return tag("html",
lst(
tag("head"),
tag("body",
lst(
fif(x == 1, tag("h1", "This is the headline"), tag("h1", "No, THIS is the headline")),
tag("p", "This is the article"),
tag("p",
tag("a", "Click here for more", ["href", "http://nowhere.com"]))))))
print gen(1)
这种情况开始出现故障的地方是循环。任何循环都必须被提取到一个单独的函数中。你觉得怎么样?有趣还是愚蠢?试试看&告诉我你的想法。你应该对每个文本节点、属性值等进行html转义,否则html注入和XSS会咬你 除了功能齐全的模板系统(mako、genhi、chameleon、jinja等)之外,与您所做的更相似的库可能是lxml
>>> from lxml.html.builder import HTML, HEAD, BODY, H1, P, A
>>> from lxml.html import tostring
>>>
>>> h = HTML(
... HEAD(
... BODY(
... H1('This is the headline'),
... P('This is the article'),
... P(
... A('Click here for more', href='http://nowhere.com')))))
>>> print tostring(h, pretty_print=True)
<html><head><body>
<h1>This is the headline</h1>
<p>This is the article</p>
<p><a href="http://nowhere.com">Click here for more</a></p>
</body></head></html>
好吧,这不属于电视,因为这不是一个问题。你到底想听什么?它毕竟不太实用……您的
fif
只返回一个结果,但在调用它之前会对这两个结果进行评估。
def gen(x):
"""Sample function demonstratine conditional HTML generation. Looks just like CL-WHO!"""
return tag("html",
lst(
tag("head"),
tag("body",
lst(
fif(x == 1, tag("h1", "This is the headline"), tag("h1", "No, THIS is the headline")),
tag("p", "This is the article"),
tag("p",
tag("a", "Click here for more", ["href", "http://nowhere.com"]))))))
print gen(1)
>>> from lxml.html.builder import HTML, HEAD, BODY, H1, P, A
>>> from lxml.html import tostring
>>>
>>> h = HTML(
... HEAD(
... BODY(
... H1('This is the headline'),
... P('This is the article'),
... P(
... A('Click here for more', href='http://nowhere.com')))))
>>> print tostring(h, pretty_print=True)
<html><head><body>
<h1>This is the headline</h1>
<p>This is the article</p>
<p><a href="http://nowhere.com">Click here for more</a></p>
</body></head></html>
H1("This is the headline" if x==1 else "No, THIS is the headline")