我不知道这是聪明还是愚蠢。我喜欢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",
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>看起来就像CL-WHO,但使用了函数表示法而不是s表达式。所以我从这个标签生成函数开始:
def tag(name, inner="", attribs=[], close=True):
ret = []
ret.append('<' + name)
while attribs.__len__() > 0:
ret.append(' %s="%s"' % (attribs.pop(0),attribs.pop(0)))
ret.append(">")
if type(inner).__name__ == 'list':
ret.extend(inner)
else:
ret.append(inner)
if close:
ret.append('</%s>' % name)
return "".join(ret)inner可以是list,list的方括号在所有Lispy代码中都很难看,所以我想要一个根据参数创建list的函数:
def lst(*args):
return [x for x in args]为了便于条件代码生成,您需要一个if语句,该语句是一个函数,它的计算结果是两个结果中的一个,就像在Lisp中一样,所以您可以嵌套它。命令式的流程控制风格的if不会起作用。
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)它开始分解的地方是循环。任何循环的东西都必须被提取到一个单独的函数中。那么你觉得呢?有趣还是愚蠢?试试看&告诉我你的想法。
发布于 2011-04-16 04:27:16
你应该对每个文本节点、属性值等进行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>您可以使用三元运算符
H1("This is the headline" if x==1 else "No, THIS is the headline")https://stackoverflow.com/questions/5680697
复制相似问题