简体   繁体   中英

Display a javascript variable content from mustache

I have a page template made with mustache. The thing is that i have to translate the content of the Data into another language rather than english.

{{#variableToTranslate}}    
    <tr>
       <th>title</th>
       <td>{{variableToTranslate}}</td>
    </tr>
{{/variableToTranslate}}

to solve this, I have used a javascript function that return the translatedVariable.

My questions are:

  • How can i display the translated variable?(how can i display the return of a javascript function in a mustache template).
 <script> function translate(arg1,arg2){ return arg1+arg2;} </script> 
{{#variableToTranslate}}    
    <tr>
        <th>title</th>
        <td>translate(arg1,arg2);</td>
    </tr>
{{/variableToTranslate}} 
  • Is there a better way to translate the content of a data set before displaying it.

thank you.

Mustache templates actually supports lambdas:

From the docs: https://mustache.github.io/mustache.5.html


Lambdas

When the value is a callable object, such as a function or lambda, the object will be invoked and passed the block of text. The text passed is the literal block, unrendered. {{tags}} will not have been expanded - the lambda should do that on its own. In this way you can implement filters or caching.

Template:

{{#wrapped}}
  {{name}} is awesome.
{{/wrapped}}

Hash:

{
  "name": "Willy",
  "wrapped": function() {
    return function(text, render) {
      return "<b>" + render(text) + "</b>"
    }
  }
}

Output:

<b>Willy is awesome.</b>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM