Python金字塔和变色龙模板语言转义为html [英] Python Pyramid & Chameleon templating language escapes html
问题描述
我无法理解变色龙的标签.我是django使用者,但决定将我的CompSci课程伙伴和我自己介绍给Pyramid,因为我虽然更轻巧=更容易学习.
I can't make sense of chameleon's tags. I'm a django user, but decided to introduce my CompSci course mates and myself to Pyramid, since I though more lightweight = easier to learn.
目前,$ {}标签正在转义我试图通过其输出的所有html标签.在django中,有一种方法可以指定变量安全"并且不需要转义.
At the moment the ${} tag is escaping any html tags I'm trying to output through it. In django there was some way to specify that a variable is "safe" and doesn't need to be escaped.
我如何在金字塔/变色龙中做同样的事情?
How can I do the same thing in Pyramid / Chameleon?
推荐答案
变色龙基于 Zope页面模板库,因此,如果您缺少Chameleon文档,则不妨查看zpt文档.
Chameleon is based on the Zope Page Templates library, so if you find the Chameleon documentation lacking, you might wish to check out the zpt docs.
在任何情况下,有两种主要方法可以执行此操作.如果使用tal:replace或tal:content标记属性进行渲染,则可以使用.这是通过在字符串的开头放置structure
,后跟一个空格以及最后要渲染的模板变量的名称来完成的.一个示例如下所示:
In any case, there are two main ways to do this. If you are rendering using a tal:replace or tal:content tag attribute, you can use a "structure". This is done by putting structure
at the beginning of the string, followed by a space, and finally the name of the template variable you wish to render. An example is shown below:
s = '''
<html>
<head>
</head>
<body>
<div tal:content="structure t">
</div>
</body>
</html>
'''
from chameleon import PageTemplate
pt = PageTemplate(s)
print pt(t='<p>Hi!</p>')
如果您不想使用tal:replace或tal:content函数,则需要将字符串包装在Chameleon渲染器将不会尝试转义的对象中(这意味着它具有__html__
方法,该方法返回字符串应该是什么).通常,这意味着创建一个文学"类,如下所示:
If you don't want to use the tal:replace or tal:content functions, you need to wrap your string in an object that the Chameleon renderer will not try to escape (meaning it has an __html__
method that returns what the string should be). Typically, this means creating a 'Literal' class as shown below:
a = '''
<html>
<head>
</head>
<body>
<div>
${t}
</div>
</body>
</html>
'''
from chameleon import PageTemplate
pt = PageTemplate(a)
class Literal(object):
def __init__(self, s):
self.s =s
def __html__(self):
return self.s
print pt(t=Literal('<p>Hi!</p>'))
这篇关于Python金字塔和变色龙模板语言转义为html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!