Expressions and nested expressions in dust.js?

I would like to add a value to dust.js as follows:

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

What I know, I can do it with an assistant (terribly detailed)

  this is x+1 : {@math key="x" method="add" operand="1" /} 

What can I live with (but not happy)

But what about when I want to insert a parameter?

  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 

Can this be done? I am tempted to try and fix this in the main library because it is very annoying to me.

What other ways to do this? Creating temporary variables (for example, {xplus1})? My real solution is to move any / all logic to helpers - I write a lot of helpers.


update:

I wrote a helper that can create variables with scope. This seems like a clean way to do it.

  {@eval xplus1="{x} + 1"} ... scope where x = x+1 this is x+1 : {xplus1} {/eval} 

He is currently using JavaScript eval, but I am considering using a JS math library like JavaScript Expression Evaluator or math.js

+4
source share
2 answers

In addition to Tom's solution, here is another implementation of the eval helper that evaluates the containing block.

For example, if in your context there is a variable a = 5 and b = 10 ,

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

will be displayed as 115 .

You can also make these estimates:

 {@eval}{a} + {b} + {@eval}{a} + {b} + 100{/eval}{/eval} //Would render 130 

Here is the code:

 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; } 
+4
source

here is "eval" - I'm afraid I have not tested it, but it should work. add this to https://github.com/linkedin/dustjs-helpers/blob/master/lib/dust-helpers.js along with other helpers.

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

you must include dust-helpers.js as well as the main dust js file.

+1
source

Source: https://habr.com/ru/post/1482078/


All Articles