4

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

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

我知道我可以用一个助手来做到这一点(非常冗长)

 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,但我正在考虑使用 JS 数学库,如JavaScript Expression Evaluatormath.js

4

2 回答 2

4

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

例如,如果您有一个变量a = 5并且b = 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;
}
于 2013-07-30T20:37:40.803 回答
1

这是'eval'-恐怕我没有测试它,但它应该可以工作。将其与其他助手一起添加到https://github.com/linkedin/dustjs-helpers/blob/master/lib/dust-helpers.js中。

"eval" : function( chunk, context, bodies, params ){
        var body = bodies.block, exp, param, exps = {};        
        for(param in params){
          if(Object.hasOwnProperty.call(params,param)){
               exp = dust.helpers.tap(param, chunk, context);               
               exps[param]=eval(exp);            
          }
        }
        if(body) {
         context = context.push(exps);
         return chunk.render( bodies.block, context );
        }
        else {
         _console.log( "Missing body block in the eval helper!" );
         return chunk;
        }
    };

您必须包含dust-helpers.js 以及主要的dust js 文件。

于 2013-07-30T19:09:54.157 回答