gpt4 book ai didi

python - 了解 pystache 中的 lambda

转载 作者:行者123 更新时间:2023-12-04 03:08:18 27 4
gpt4 key购买 nike

假设我想在 pystache 中编写一个格式为 2 位 float 的函数。

我想要上下文中的 float 和函数(我相信这是 Mustache 的正确哲学)。

我该怎么办?

为了把问题说清楚,我将展示我写的一对代码片段。它们不起作用。

片段(a):

import pystache

tpl = "{{#fmt}}{{q}}{{/fmt}}"

ctx = {
'q' : 1234.5678,
'fmt' : lambda x: "%.2f" % float(x)
}

print pystache.render(tpl, ctx)

这失败了,错误是“无法将字符串转换为 float :{{q}}”。我能理解这个错误:{{fmt}} 在 {{q}} 之前求值。

片段(b):

import pystache

tpl = "{{#q}}{{fmt}}{{/q}}"

ctx = {
'q' : 1234.5678,
'fmt' : lambda x: "%.2f" % float(x)
}

print pystache.render(tpl, ctx)

这失败并出现错误:“lambda() 恰好接受 1 个参数(给定 0)”。我无法理解这个错误:上下文不应该作为参数传递吗?

最佳答案

简短回答:mustache 不支持这个。它期望所有数据值都经过预处理。

2012 年,在 formating of dates, numbers and more · Issue #41 · mustache/spec , ppl suggested 各种实现,包括。来自其他模板引擎,无法得出任何结论。

根据 mustache.js date formatting , ppl 已经构建了几个扩展和/或解决方法(对我来说,最有希望的是 {{value | format}} syntax extension ),或者建议转移到其他标记引擎。


附加信息:

规范在 http://mustache.github.io/mustache.5.html (链接自 http://mustache.github.io 头版)已过时,日期为 2009。pystache 遵循的最新规范位于 https://github.com/mustache/spec。 ,看起来也被遗弃了:最新的提交日期为 02.2015 和 the latest spec update来自 2011 年。Nor does it have a successor .

因此,至此,标准已经失效,因此标记可以免费供所有人使用。

我仍然建议在重新发明轮子之前考虑与上述讨论相关的其他格式。

关于python - 了解 pystache 中的 lambda,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47099348/

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