当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Ractive template if statement doesn't take parent if statements into account

问题描述:

In my template I've got an if statement for a string which is sometimes undefined as it's inside a loop and the items in the loop are removed and added to when other events happen.

Below is an example template that would be a partial inside a loop. This partial causes undefined errors in RactiveJS when changing myString to undefined from a value in the JS.

{{#if myString}}

{{#if myString.indexOf('hello people') > -1}}

<p>Hello all the people</p>

{{/if}}

Why are the people?

{{/if}}

To stop errors I would have to do the following:

{{#if myString}}

{{#if myString && myString.indexOf('hello people') > -1}}

<p>Hello all the people</p>

{{/if}}

Why are the people?

{{/if}}

This template with the && in the child if statement doesn't make much sense to me as it should take the parent if statement into account and not cause an error.

Is there something wrong in the way Ractive's translates if statements or is this normal for a templating language?

网友答案:

The current version of Ractive 'flattens' the graph of things that depend on your data; a side-effect of that is that expressions are sometimes updated immediately before they're removed, which results in undesirable situations like this one. This is likely to change in the next version (0.8). For now, the best workaround is probably the one you're already using, though you could also encapsulate it as a function if that makes the template more readable:

{{#if isHelloPeople(myString) }}
    <p>Hello all the people</p>
{{/if}}
var ractive = new Ractive({
  data: {
    myString: 'hello people',
    isHelloPeople: function ( str ) {
      return str && ~str.indexOf( 'hello people' );
    }
  },
  // ...
});
分享给朋友:
您可能感兴趣的文章:
随机阅读: