首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python中的CL-WHO :聪明还是愚蠢?

Python中的CL-WHO :聪明还是愚蠢?
EN

Stack Overflow用户
提问于 2011-04-16 02:10:59
回答 1查看 206关注 0票数 0

我不知道这是聪明还是愚蠢。我喜欢CL-WHO,我也喜欢Python,所以我一直在研究一种将两者混合在一起的方法。我想说的是:

代码语言:javascript
复制
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"]))))))

并将其计算为:

代码语言:javascript
复制
<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表达式。所以我从这个标签生成函数开始:

代码语言:javascript
复制
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的函数:

代码语言:javascript
复制
def lst(*args):
  return [x for x in args]

为了便于条件代码生成,您需要一个if语句,该语句是一个函数,它的计算结果是两个结果中的一个,就像在Lisp中一样,所以您可以嵌套它。命令式的流程控制风格的if不会起作用。

代码语言:javascript
复制
def fif(cond, a, b):
  if cond:
    return a
  else:
    return b

维奥拉。现在您可以生成示例页面,如下所示:

代码语言:javascript
复制
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)

它开始分解的地方是循环。任何循环的东西都必须被提取到一个单独的函数中。那么你觉得呢?有趣还是愚蠢?试试看&告诉我你的想法。

EN

回答 1

Stack Overflow用户

发布于 2011-04-16 04:27:16

你应该对每个文本节点、属性值等进行html转义,否则html注入和XSS就会咬你一口。

除了功能齐全的模板系统(mako、genhi、chameleon、jinja等)之外,与您所做的更相似的库可能是lxml

代码语言:javascript
复制
>>> 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>

您可以使用三元运算符

代码语言:javascript
复制
H1("This is the headline" if x==1 else "No, THIS is the headline")
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5680697

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档