Search code examples
javascriptjsontemplate-enginejsrenderjsviews

jsViews / jsRender vs rich expressions inside template


Quick question: I'm using jsViews to render HTML template. I want to have some kind of translation. Right now my application returns global variable "language" with value which is equal to: pl || en || de.

How to use global variable "language" to reduce data in JSON responsible for translation?

1). JSON Data

    var language = [
  {
    "pl": {
            "prop": "value",
            "prop": "value"
    },
    "en": {
            "prop": "value",
            "prop": "value"
    },
    "de": {
            "prop": "value",
            "prop": "value"
    }
  }
];

2). Working HTML template but language value is written statically

<script type="text/x-jsrender" id="test">
    <div>
        {{props pl}}
        <span>
            {{>prop}}
        </span>
        {{/props}}
    </div>
</script> 

3). I want to change {{props pl}} into something like {{props *language}} to get language dynamically in template but how to write it correctly?

I know that:

  a). $.views.settings.allowCode= true;        
  b). {{*:language}} will return language shortcode

So how to use this expression inside {{if}} or {{props}} or {{for}} ??

Thank you in advance!!


Solution

  • Using allowCode = true is best for cases where you want include code for operations that are not achievable declaratively.

    You can mix code and regular tags, as shown in examples here: http://www.jsviews.com/#allowcodetag;

    But avoiding allowCode will give better maintainability and code separation.

    If in this case if all you want is to access globals, you can simply pass them in, or declare them, as helpers: http://www.jsviews.com/#helpers.

    For example you could do:

    <input data-link="~options.language" />
    
    <div>
        {^{props words[~options.language]}}
        <span>
            {{>prop}}
        </span>
        {{/props}}
    </div>
    

    and

    var data = {
      words: {
        en: {
          prop: "value",
          prop: "value"
        },
        de: {
          ...
      }};
    
    $.templates("#test").link('#container', data, {options: {language: "en"}});
    

    Now if you change the language in the input, the props display will switch to the new language.