Sendgrid 的电子邮件模板是使用 Handlebars 呈现的。在 Sendgrid 的 Handlebars 实现中,有 #equals 助手。我正在使用 Python 的 pybars3。在 pybars3 的 GitHub 自述文件中,有一个如何添加助手的示例。如何将 Sendgrid 中的 #equals 帮助程序实现到我的 pybars3 代码中?
我希望它接受以下 HTML,并且根据
number_of_plans
变量,输出“您的计划”或“您的计划”。
Your {{#equals number_of_plans 1}}Plan{{else}}Plans{{/equals}}
我认为它应该看起来像这样:
# Get a compiler
from pybars import Compiler
compiler = Compiler()
# helper function; this isn't quite right
def _equals(this, options, v1, v2):
if v1 == v2:
options['fn']
else:
options['inverse']
helpers = {'equals': _equals}
# Compile the template
source = r'Your {{#equals number_of_plans 1}}Plan{{else}}Plans{{/equals}}'
template = compiler.compile(source)
# render the template
output = template({'number_of_plans': 1}, helpers = helpers)
但是,输出是“您的计划”,而不是“您的计划”。我做错了什么?
我也遇到过这个问题。事实证明,您实际上必须使用上下文(您的变量列表)来调用它。所以,结果可能如下:
def _equal(this: Dict[str, Any], options: Dict[str, Any], a: str, b: str) -> Any:
if a == b:
return options["fn"](this)
return options["inverse"](this)
其中
a
和 b
当然是值。
[我不确定输入的内容,所以我返回 Any。]