add option for custom index variable in react templates (fixes #88)

This commit is contained in:
Omer Ganim 2016-05-15 16:36:53 +03:00
parent 5b6eb7222c
commit dc9e84e99b
5 changed files with 30 additions and 5 deletions

View File

@ -126,8 +126,9 @@ define([
```
## rt-repeat
Repeats a DOM node with its subtree for each item in an array. The syntax is `rt-repeat="itemVar in arrayExpr"`, where the element, `itemVar`, will be available in JavaScript context,
Repeats a DOM node with its subtree for each item in an array. The syntax is `rt-repeat="itemVar, indexVar in arrayExpr"`, where the element, `itemVar`, will be available in JavaScript context,
and an `itemVarIndex` will be created to represent the index of the item. By using this naming scheme, repeated expressions have access to all levels of nesting.
It is also possible to declare a custom index variable using the syntax `rt-repeat="itemVar, indexVar in arrayExpr"`, in which case the index variable will be `indexVar`.
###### Sample:
```html

View File

@ -316,11 +316,16 @@ function convertHtmlToReact(node, context) {
if (arr.length !== 2) {
throw RTCodeError.build(context, node, `rt-repeat invalid 'in' expression '${node.attribs[repeatAttr]}'`);
}
data.item = arr[0].trim();
const repeaterParams = arr[0].split(',').map(s => s.trim());
data.item = repeaterParams[0];
data.index = repeaterParams[1] || `${data.item}Index`;
data.collection = arr[1].trim();
validateJS(data.item, node, context);
const bindParams = [data.item, data.index];
_.forEach(bindParams, param => {
validateJS(param, node, context);
});
validateJS(`(${data.collection})`, node, context);
[data.item, `${data.item}Index`].forEach(param => {
_.forEach(bindParams, param => {
if (!_.includes(context.boundParams, param)) {
context.boundParams.push(param);
}

View File

@ -0,0 +1,3 @@
<ul>
<li rt-repeat="item, customIndex in this.props.collection">{item} is number {customIndex}</li>
</ul>

View File

@ -0,0 +1,16 @@
define([
'react',
'lodash'
], function (React, _) {
'use strict';
function repeatItem1(item, customIndex) {
return React.createElement('li', {}, item, ' is number ', customIndex);
}
return function () {
return React.createElement.apply(this, [
'ul',
{},
_.map(this.props.collection, repeatItem1.bind(this, customIndex))
]);
};
});

View File

@ -29,7 +29,7 @@ module.exports = {
});
test('conversion test', t => {
const files = ['div.rt', 'test.rt', 'repeat.rt', 'inputs.rt', 'virtual.rt', 'stateless.rt'];
const files = ['div.rt', 'test.rt', 'repeat.rt', 'repeat-with-index.rt', 'inputs.rt', 'virtual.rt', 'stateless.rt'];
testFiles(t, files);
});