gpt4 book ai didi

python - web2py 中的 HTML 模板解析

转载 作者:行者123 更新时间:2023-11-30 23:33:06 25 4
gpt4 key购买 nike

我正在尝试解决这个 web2py 问题,但我认为我对正在发生的事情有一些基本的误解。

假设我有一家商店,我希望在我的 index.html 中有许多装有产品的盒子。我希望从模板中解析每个这样的框。

我试图做的是拥有以下架构。在 Controller 中我有

def index():
products = db().select(db.products.ALL)
return dict(products=products)

index.html中:

{{for i in range(0,len(products)):}}
{{ context=dict(product=products[i]) }}
{{ =response.render('template.html', context)}}
{{pass}}

template.html中我有类似的东西

<div id=...> <h1> {{=product.price}} </h1>...

问题在于结果是按字面意思读取的。也就是说,当浏览 index.html 时,我看到 html 标签:

enter image description here

我怀疑我的整个方法都是错误的。应该怎样做呢?

最佳答案

{{for product in products:}}
{{=XML(response.render('template.html', product.as_dict()))}}
{{pass}}

在 template.html 中:

<div id=...> <h1> {{=price}} </h1>...

response.render() 返回一个字符串,所有字符串在模板中都被转义。为了防止转义,您必须将字符串包装在 XML() 中。

上面还包括一​​些简化。在 for 循环中,您可以直接迭代 products 中的行,然后可以将单个产品行转换为字典并将该字典作为上下文传递给template.html(因此您可以只引用 price 而不是 product.price)。

请注意,如果您不需要在其他地方使用 template.html,您不妨将其内容直接移至 index.html 中的 for 循环中。

关于python - web2py 中的 HTML 模板解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19104896/

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