HTML插入的Python速记

2024-06-06 17:11:11 发布

您现在位置:Python中文网/ 问答频道 /正文

在文件中我们发现:

${...} 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而不是文本?你知道吗


Tags: 文件thetextdivforiscontentoperator
1条回答
网友
1楼 · 发布于 2024-06-06 17:11:11

要避免转义,请使用structure:前缀:

<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__方法应该如何工作的示例。请注意,我不是变色龙用户,此代码未经测试:)

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

    def __html__(self):
        return self.value

在模板中:

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

相关问题 更多 >