gpt4 book ai didi

python - 如何将 html 字符串转储到 python 扭曲模板中

转载 作者:太空宇宙 更新时间:2023-11-04 01:21:01 26 4
gpt4 key购买 nike

我正在使用 twisted.web.template 制作一个网站,其中多个页面的子窗口具有相同的 html 代码。所以我想使用模板,只要有相同的代码,就将一个完整的 html 字符串转储到占位符中。但是扭曲的模板系统引用了这些字符串(部分原因似乎是出于安全原因),因此浏览器无法将其解释为 html。有什么办法解决这个问题吗?这似乎是一个非常正常的使用场景,根据我的经验,这是 php 与 apache 的基本用法之一......

一些示例代码。我的模板看起来像这样

<html xmlns:t="http://twistedmatrix.com/ns/twisted.web.template/0.1">
<body>
<div t:render="content" />
</body>
</html>

和我在 python 中的渲染类

class ExampleElement(Element):
loader = XMLFile(FilePath('template.xml'))

@renderer
def content(self, request, tag):
return tag('<b>This content should be in bold, but is quoted</b>')

我知道我可以写的最后一行(通过适当的导入)

return tag(tags.b('Bold content'))

但是我实际上想要放入的 html 字符串要大得多,而且不得不这样写很不方便,而不是仅仅一个原始的 html 字符串

最佳答案

使用加载器:

class ExampleElement(Element):
loader = XMLFile(FilePath('template.xml'))

extraContent = XMLFile(FilePath('extra-content.xml'))

@renderer
def content(self, request, tag):
return self.extraContent.load()

或者如果您真的需要将额外的内容放在源文件的字符串中而不是模板文件中:

class ExampleElement(Element):
loader = XMLFile(FilePath('template.xml'))

extraContent = XMLString("<b>This content will be in bold</b>")

@renderer
def content(self, request, tag):
return self.extraContent.load()

关于python - 如何将 html 字符串转储到 python 扭曲模板中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21263453/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com