dust.js
2013-05-22 54 views 4 likes 
4

我希望能够在dust.js添加值是这样的:表达式和嵌套表达式在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数学LIB像JavaScript Expression Evaluator或​​

+0

有趣的是,我有完全一样的问题。你有公开的eval助手的源代码吗? – quentinadam

+0

嗨goldmine - 我的实现实际上是在GWT中 - 但让我看看我是否可以复制它并转换为JS –

回答

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; 
     } 
    }; 

您必须包括防尘helpers.js以及主要的灰尘js文件。

+0

你去@goldmine - 让我知道它是否适合你。这是我在GWT实现中使用的基本逻辑。 –

+0

谢谢你,这是非常有益的! – quentinadam

4

除了汤姆的解决方案,这里还有一个eval帮助器的实现,用于评估包含块。

例如,如果你有一个变量a = 5和您的上下文b = 10

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

将呈现为115

您也可以编写那些evals:

{@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; 
} 
相关问题