Light weight templates for react
Go to file
ido 1269ecb071 update doc with rt-scope changes 2015-09-03 11:11:43 +03:00
bin error handling + test 2014-12-02 14:30:06 +02:00
docs replace the json notation with javascript 2015-08-20 11:50:19 +03:00
img added "fork me on github" ribbon 2014-12-31 18:32:23 +02:00
internalTasks fix release task 2015-01-22 16:57:48 +02:00
playground add lodash3 rules 2015-08-19 13:45:00 +03:00
sample Enabled site to work on HTTPS 2015-07-29 18:01:52 +03:00
src fixed #63 2015-09-03 10:53:48 +03:00
test test fix for #63 2015-09-03 11:01:01 +03:00
.eslintrc lodash eslint rules 2015-08-25 17:15:02 +03:00
.gitignore Merge branch 'scope-variable-references' of https://github.com/anchann/react-templates into anchann-scope-variable-references 2015-07-30 13:40:39 +03:00
.npmignore publish to npm 2014-12-30 18:10:18 +02:00
.travis.yml fix legacy build on travis 2015-08-18 14:30:47 +03:00
CONTRIBUTING.md Update markdown files 2015-07-30 17:49:11 +03:00
Gruntfile.js add lodash3 rules 2015-08-19 13:45:00 +03:00
LICENSE Initial commit 2014-11-10 12:47:49 +02:00
README.md update doc with rt-scope changes 2015-09-03 11:11:43 +03:00
fiddle.html upgrade lodash to 3.10 2015-07-30 16:05:53 +03:00
home.config.js Enabled site to work on HTTPS 2015-07-29 18:01:52 +03:00
index.html Set the 'fork-me' ribbon link to open in a new tab 2015-07-30 17:51:44 +03:00
package.json lodash eslint rules 2015-08-25 17:15:02 +03:00
playground.config.js Enabled site to work on HTTPS 2015-07-29 18:01:52 +03:00

README.md

NPM version build status Coverage Status

React Templates

Lightweight templates for React.

  • No runtime libraries. No magic. Simply precompile your way to clear React code.
  • Easy syntax that's similar to HTML, supported by most IDEs.
  • Clear separation of presentation and logic - almost zero HTML in component files.
  • Declarative coding ensures that the HTML that you write and the HTML you inspect look nearly identical.
  • Supports AMD, CommonJS, ES6, Typescript and globals.

How does it work

React Templates compiles an *.rt file (react template file - an extended HTML format) into a JavaScript file. This file, which uses AMD syntax, returns a function. When invoked, this function returns a virtual React DOM based on React.DOM elements and custom user components.

A common use case would be that a regular React component would require a JavaScript file generated from a template, and then perform `func.apply(this)`, causing the template to have that component as its context.

Playground

http://wix.github.io/react-templates/

Yeoman generator

https://github.com/wix/generator-react-templates

Hello react-templates

Here's a sample Hello project:
https://github.com/wix/hello-react-templates

IntelliJ / WebStorm plugin

http://plugins.jetbrains.com/plugin/7648

Basic concepts for React templates
Why not use JSX?

Some love JSX, some don't. We don't. More specifically, it seems to us that JSX is only a good fit for components with very little HTML inside. And this can be accomplished by creating DOM elements in code. Also, we like to separate code and HTML because it just feels right.

Installation

You can install react-templates using npm:

npm install react-templates -g

Usage

rt [file.rt|dir]* [options]

See more on CLI usage here.

In most cases, this package will be wrapped in a build task, so CLI will not be used explicitly:

Use React Templates for Native Apps?

You can get all the react templates functionality and more. Click here for more info

Template directives and syntax

Any valid HTML is a template

Any HTML that you write is a valid template, except for inline event handlers ("on" attributes). See the "event handlers" section below for more information.

{} to identify JavaScript expressions

To embed JavaScript expressions in both attribute values and tag content, encapsulate them in {}. If this is done inside an attribute value, the value still needs to be wrapped in quotes. For directives (see below), {} are not used.

Sample:
<a href="{this.state.linkRef}">{this.state.linkText}</a>
Compiled:
define([
    'react',
    'lodash'
], function (React, _) {
    'use strict';
    return function () {
        return React.DOM.a({ 'href': this.state.linkRef }, this.state.linkText);
    };
});

rt-if

This lets you add conditions to a subtree of HTML. If the condition evaluates to true, the subtree will be returned; otherwise, it will not be calculated. It is implemented as a ternary expression.

Sample:
<div rt-if="this.state.resultCode === 200">Success!</div>
Compiled:
define([
    'react',
    'lodash'
], function (React, _) {
    'use strict';
    return function () {
        return this.state.resultCode === 200 ? React.DOM.div({}, 'Success!') : null;
    };
});

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, 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.

Sample:
<div rt-repeat="myNum in this.getMyNumbers()">{myNumIndex}. {myNum}</div>
Compiled:
define([
    'react',
    'lodash'
], function (React, _) {
    'use strict';
    function repeatMyNum1(myNum, myNumIndex) {
        return React.DOM.div({}, myNumIndex + '. ' + myNum);
    }
    return function () {
        return _.map(this.getMyNumbers(), repeatMyNum1.bind(this));
    };
});

rt-scope

This directive creates a new JavaScript scope by creating a new method and invoking it with its current context. The syntax is rt-scope="expr1 as var1; expr2 as var2. This allows for a convenient shorthand to make the code more readable. It also helps to execute an expression only once per scope.

Sample:
<div rt-repeat="rpt in array">
    <div rt-scope="')' as separator; rpt.val as val">{rptIndex}{separator} {val}</div>
    <div>'rpt' exists here, but not 'separator' and 'val'</div>
</div>
Compiled:
define([
    'react',
    'lodash'
], function (React, _) {
    'use strict';
    function scopeSeparatorVal1(rpt, rptIndex, separator, val) {
        return React.DOM.div({}, rptIndex + separator + ' ' + val);
    }
    function repeatRpt2(rpt, rptIndex) {
        return React.DOM.div({}, scopeSeparatorVal1.apply(this, [
            rpt,
            rptIndex,
            ')',
            rpt.val
        ]), React.DOM.div({}, '\'rpt\' exists here, but not \'separator\' and \'val\''));
    }
    return function () {
        return _.map(array, repeatRpt2.bind(this));
    };
});

Subsequent expressions may reference preceding variables, since generated code declares each alias as a var (as opposed to a function parameter, which get bound to formal parameter names only after evaluation), so you can do stuff like

<div rt-scope="users[userId] as user; user.profile as profile; profile.avatar as avatar;">

When used with rt-if, the rt-if condition is evaluated first, and only if it is truthy, the rt-scope mappings are processed. This means you can write things like

<div rt-if="user.profile" rt-scope="user.profile.image as image">

without risking accessing a field on an undefined, or doing something ugly like user.profile && user.profile.image as image.

When used with rt-repeat, the rt-scope is evaluated for every iteration, so that iteration's item and itemIndex are in scope.

rt-props

rt-props is used to inject properties into an element programmatically. It will merge the properties with the properties received in the template. This option allows you to build properties based on external logic and pass them to the template. It is also useful when passing properties set on the component to an element within the template. The expected value of this attribute is an expression returning an object. The keys will be the property name, and the values will be the property values.

Sample:
<input style="height:10px;width:3px;" rt-props="{style:{width:'5px'},type:'text'}"/>
Compiled:
define([
    'react',
    'lodash'
], function (React, _) {
    'use strict';
    return function () {
        return React.DOM.input(_.merge({}, {
            'style': {
                height: '10px',
                width: '3px'
            }
        }, {
            style: { width: '5px' },
            type: 'text'
        }));
    };
});

rt-class

To reduce the boilerplate code when setting class names programatically, you can use the rt-class directive. It expects a JSON object with keys as class names, and a Boolean as the value. If the value is true, the class name will be included.

Note the following:
1. In React templates, you can use the "class" attribute as you would in HTML.
2. If you use both class and rt-class on the same HTML element, they get merged.

Sample:
<div rt-scope="{blue: true, selected: this.isSelected()} as classes">
    These are logically equivalent
    <div rt-class="classes">Reference</div>
    <div rt-class="{blue: true, selected: this.isSelected()}">Inline</div>
    <div class="blue{this.isSelected() ? ' selected' : ''}">Using the class attribute</div>
</div>
Compiled:
define([
    'react',
    'lodash'
], function (React, _) {
    'use strict';
    function scopeClasses1(classes) {
        return React.DOM.div({}, 'These are logically equivalent', React.DOM.div({ 'className': React.addons.classSet(classes) }, 'Reference'), React.DOM.div({
            'className': React.addons.classSet({
                blue: true,
                selected: this.isSelected()
            })
        }, 'Inline'), React.DOM.div({ 'className': 'blue' + this.isSelected() ? ' selected' : '' }, 'Using the class attribute'));
    }
    return function () {
        return scopeClasses1.apply(this, [{
                blue: true,
                selected: this.isSelected()
            }]);
    };
});

style

React templates allow the settings of styles inline in HTML, optionally returning an object from the evaluation context. By default, style names will be converted from hyphen-style to camelCase-style naming.

To embed JavaScript inside a style attribute, single curly braces are used. To embed an entire object, double curly braces are used. Note: When embedding objects, styles must conform to camelCase-style naming.

Sample:
<div>
    These are really equivalent
    <div style="color:white; line-height:{this.state.lineHeight}px">Inline</div>
    <div style="{{'color': 'white', 'lineHeight': this.state.lineHeight + 'px'}}">Inline</div>
</div>
Compiled:
define([
    'react',
    'lodash'
], function (React, _) {
    'use strict';
    return function () {
        return React.DOM.div({}, 'These are really equivalent', React.DOM.div({
            'style': {
                color: 'white',
                lineHeight: this.state.lineHeight + 'px'
            }
        }, 'Inline'), React.DOM.div({
            'style': {
                'color': 'white',
                'lineHeight': this.state.lineHeight + 'px'
            }
        }, 'Inline'));
    };
});

event handlers

React event handlers accept function references inside of {}, such as onClick="{this.myClickHandler}". When functions are not needed, lambda notation can be used, which will create a React template that creates a function for the included code. There is no performance impact, as the function created is bound to the context instead of being recreated.

The lambda notation has the form: `onClick="(evt) => console.log(evt)"`. In this example, **evt** is the name of the first argument passed into the inline function. With browser events, this will most likely be the React synthetic event. However, if you expect a property that starts with **on**Something, then React templates will treat it as an event handler. If you have an event handler called **onBoxSelected** that triggers an event with row and column params, you can write `onBoxSelected="(row, col)=>this.doSomething(row,col)"`. A no-param version is supported as well: `onClick="()=>console.log('just wanted to know it clicked')"`.

Sample:
<div rt-repeat="item in items">
    <div onClick="()=>this.itemSelected(item)" onMouseDown="{this.mouseDownHandler}">
</div>
Compiled:
define([
    'react',
    'lodash'
], function (React, _) {
    'use strict';
    function onClick1(item, itemIndex) {
        this.itemSelected(item);
    }
    function repeatItem2(item, itemIndex) {
        return React.DOM.div({}, React.DOM.div({
            'onClick': onClick1.bind(this, item, itemIndex),
            'onMouseDown': this.mouseDownHandler
        }));
    }
    return function () {
        return _.map(items, repeatItem2.bind(this));
    };
});

rt-require, and using other components in the template

In many cases, you'd like to use either external code or other components within your template. An rt-require tag lets you include dependencies: <rt-require dependency="depVarPath" as="depVarName"/>. Once included, depVarName will be in scope. You can only use rt-require tags at the beginning of your template. When including React components, they can be referred to by their tag name inside a template. For example, <MySlider prop1="val1" onMyChange="{this.onSliderMoved}">. Nesting is also supported: <MyContainer><div>child</div><div>another</div></MyContainer>. Children are accessible from this.props.children.

Sample:
<rt-require dependency="comps/myComp" as="MyComp"/>
<rt-require dependency="utils/utils" as="utils"/>
<MyComp rt-repeat="item in items">
    <div>{utils.toLower(item.name)}</div>
</MyComp>
Compiled (AMD):
define([
    'react/addons',
    'lodash',
    'comps/myComp',
    'utils/utils'
], function (React, _, MyComp, utils) {
    'use strict';
    function repeatItem1(item, itemIndex) {
        return React.createElement(MyComp, {}, React.createElement('div', {}, utils.toLower(item.name)));
    }
    return function () {
        return _.map(items, repeatItem1.bind(this));
    };
});
Compiled (with CommonJS flag):
var React = require('react/addons');
var _ = require('lodash');
var MyComp = require('comps/myComp');
var utils = require('utils/utils');
'use strict';
function repeatItem1(item, itemIndex) {
    return React.createElement(MyComp, {}, React.createElement('div', {}, utils.toLower(item.name)));
}
module.exports = function () {
    return _.map(items, repeatItem1.bind(this));
};
Compiled (with ES6 flag):
import React from 'react/addons';
import _ from 'lodash';
import MyComp from 'comps/myComp';
import utils from 'utils/utils';
function repeatItem1(item, itemIndex) {
    return React.createElement(MyComp, {}, React.createElement('div', {}, utils.toLower(item.name)));
}
export default function () {
    return _.map(items, repeatItem1.bind(this));
};

Inline Templates

Although we recommend separating the templates to a separate .rt file, there's an option to use a template inline as the render method (à la JSX). To do that, write your code in a .jsrt file, and send it to react-templates with the modules flag set to jsrt.

Sample:
define(['react','lodash'], function (React, _) {
    var comp = React.createClass({
        render:
            <template>
                <div>hello world</div>
            </template>
    });

    return comp;
});

Compiled (with jsrt flag):

define([
    'react',
    'lodash'
], function (React, _) {
    var comp = React.createClass({
        render: function () {
            return function () {
                return React.createElement('div', {}, 'hello world');
            };
        }()
    });
    return comp;
});

rt-template, and defining properties template functions

In cases you'd like to use a property that accepts a function and return renderable React component. You should use a rt-template tag that will let you do exactly that: <rt-template prop="propName" arguments="arg1, arg2"/>.

Templates can be used only as an immediate child of the component that it will be used in. All scope variable will be available in the template function.

Sample:
<MyComp data="{[1,2,3]}">
    <rt-template prop="renderItem" arguments="item">
        <div>{item}</div>
    </rt-template>
</MyComp>
Compiled (AMD):
define([
    'react/addons',
    'lodash'
], function (React, _) {
    'use strict';
    function renderItem1(item) {
        return React.createElement('div', {}, item);
    }
    return function () {
        return React.createElement(MyComp, {
            'data': [
                1,
                2,
                3
            ],
            'renderItem': renderItem1.bind(this)
        });
    };
});
Compiled (with CommonJS flag):
'use strict';
var React = require('react/addons');
var _ = require('lodash');
function renderItem1(item) {
    return React.createElement('div', {}, item);
}
module.exports = function () {
    return React.createElement(MyComp, {
        'data': [
            1,
            2,
            3
        ],
        'renderItem': renderItem1.bind(this)
    });
};
Compiled (with ES6 flag):
import React from 'react/addons';
import _ from 'lodash';
function renderItem1(item) {
    return React.createElement('div', {}, item);
}
export default function () {
    return React.createElement(MyComp, {
        'data': [
            1,
            2,
            3
        ],
        'renderItem': renderItem1.bind(this)
    });
};

Contributing

See the Contributing page.

License

Copyright (c) 2015 Wix. Licensed under the MIT license.