gpt4 book ai didi

dust.js - 在dust.js 中的表达式和嵌套表达式?

转载 作者:行者123 更新时间:2023-12-05 01:08:50 25 4
gpt4 key购买 nike

我希望能够像这样在dust.js 中添加一个值:

 this is x+1 : {{x}+1} //does not work  :'(

我知道我可以用 helper 做到这一点(非常冗长)
 this is x+1 : {@math key="x" method="add" operand="1" /}

我可以忍受(但不快乐)

但是当我想嵌套一个参数时呢?
 this is x+1+1 : {@math key='{@math key="x" method="add" operand="1" /}' method="add" operand="1" /} // no dice and wins ugly code prize!

this is x+1+1 : {@math key='x' method="add" operand="1"} {@math key="selectKey" method="add" operand="1" /} {/math} //still no dice - btw selectKey is an output variable for the @math helper

是否有可能做到这一点?我很想尝试在核心库中修补它,因为它让我非常恼火。

还有什么其他方法可以做到这一点?创建临时变量(即 {xplus1})?我目前的解决方案是将任何/所有逻辑移动到助手 - 我正在编写很多助手。

更新:

我编写了一个可以创建作用域变量的助手。这似乎是一种干净的方法。
   {@eval xplus1="{x} + 1"}

... scope where x = x+1
this is x+1 : {xplus1}

{/eval}

现在它正在使用 JavaScript eval,但我正在考虑使用像 JavaScript Expression Evaluator 这样的 JS 数学库。或 math.js

最佳答案

除了 Tom 的解决方案,这里还有一个 eval 的实现评估包含块的助手。

例如,如果您有一个变量 a = 5b = 10在你的情况下,

{@eval}{a} + {b} + 100{/eval}

将呈现为 115 .

您还可以编写这些评估:
{@eval}{a} + {b} + {@eval}{a} + {b} + 100{/eval}{/eval} //Would render 130

这是代码:
dust.helpers.eval = function(chunk, context, bodies) {
var expression = '';
chunk.tap(function(data) {
expression += data;
return '';
}).render(bodies.block, context).untap();
chunk.write(eval(expression));
return chunk;
}

关于dust.js - 在dust.js 中的表达式和嵌套表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16683422/

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