Skip to main content
 首页 » 编程设计

用于 HTML 插入的 Python 简写

2024年11月01日10me-sa

在文档中我们发现:

${...} operator

The ${...} notation is short-hand for text insertion. The Python-expression inside the braces is evaluated and the result included in the output (all inserted text is escaped by default):

 <div id="section-${index + 1}"> 
    ${content} 
 </div> 

To escape this behavior, prefix the notation with a backslash character: \${...}.

如何将 content 值呈现为 HTML 而不是文本?

请您参考如下方法:

为避免转义,使用结构:前缀:

<div>${structure: content}</div> 

您还可以使用 __html__ 方法传递一个对象:

Note that if an object implements the __html__ method, the result of this method will be inserted as-is (without XML escaping).

更新:

根据要求,这是我认为 __html__ 方法应该如何工作的示例。请注意,我不是 Chameleon 用户并且此代码未经测试:)

class Unescaped(object): 
    def __init__(self, value): 
        self.value = value 
 
    def __html__(self): 
        return self.value 

在你的模板中:

<div>${ Unescaped(content) }</div>