javascript - What is a good way to create a variable in JsRender? -


in jsrender template, blocks can create variables, write this:

{{if true ~myvariable=myexpensivefunction()}}   {{:~myvariable}} {{:~myvariable}} {{/if}} 

however, bogus if annoying. there better way?

if can initialize myvariable outside template, can make helper variable, , pass in:

var html = mytmpl.render(data, {myvariable:myexpensivefunction()}); 

if need initialize in specific template/data context say, can use contextual parameters, scoped template block. use tag wraps context.

if context is top-level in template, then:

  • either top-level data , can pass in helper above
  • or 'partial' template rendered anothor (layout) template, using {{sometag tmpl=.../}}, in case can set contextual parameter calling tag in other template
  • or else rendering against array

for last case can use {{include}}:

{{include ~myvariable=myexpensivefunction()}}   {{:~myvariable}} {{:~myvariable}} {{/include}} 

or can call noiteration set true:

var html = mytmpl.render(data, [helpers,] true); 

and wrap in {{for}}:

{{for ~myvariable=myexpensivefunction()}}   {{:~myvariable}} {{:~myvariable}} {{/for}} 

edit:

in particular case, based on comments added below, need initialize in context of item block within {{for somearray}} - in order item data.

(actually item block 'partial' template called using {{for somearray tmpl=...}}, basic problem same).

in scenario indeed need add {{include}} wrapper, @ top-level (for you) or within {{for}} if not doing template composition.


Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -