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
Here's a sample Hello project with webpack, es6 and hot reload:
https://github.com/wix/react-templates-transform-boilerplate
IntelliJ / WebStorm plugin
http://plugins.jetbrains.com/plugin/7648
Basic concepts for React templates
- Any valid HTML (including comments) is a template
- {} to identify JS expression
- Built-in directives:
- rt-if
- rt-repeat
- rt-scope
- rt-props
- rt-class
- rt-import
rt-require(deprecated, use rt-import)- rt-template
- rt-include
- rt-pre
- rt-virtual
- styles
- event handlers
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:
- Grunt: grunt-react-templates
- Gulp: gulp-react-templates
- Broccoli: broccoli-react-templates
- Browserify plugin: react-templatify
- Webpack loader : react-templates-loader
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:
{this.state.linkText}
Compiled:
;
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:
Success!
Compiled:
;
rt-repeat
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:
{myNumIndex}. {myNum}
Compiled:
;
rt-virtual
This directive creates as a virtual node, which will not be rendered to the DOM, but can still be used as a root for directives, e.g. rt-if
and rt-repeat
.
Sample:
For instance, to repeat several nodes at once without a shared root for each instance:
{n} {n*2}
Compiled:
;
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:
{rptIndex}{separator} {val} 'rpt' exists here, but not 'separator' and 'val'
Compiled:
;
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
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
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:
Compiled:
;
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:
These are logically equivalent Reference Inline Using the class attribute
Compiled:
;
rt-include
Optionally choose to extract static contents out of rt files.
rt-include is a "macro" that takes a text file (e.g svg/html/xml) and injects it into the file as if it was part of the original markup.
Sample:
given main.rt
:
and my-icon.svg
:
is equivalent to:
rt-pre
When using the option --normalize-html-whitespace
it allows to override the whitespace removal behaviour on a specific tag.
Sample:
given main.rt
:
here repeating whitespaces are preserved even if --normalize-html-whitespace is on here repeating whitespaces are removed if --normalize-html-whitespace is on
rt-pre
is applied automatically on <pre>
and <textarea>
tags:
Sample:
given main.rt
:
here repeating whitespaces are preserved even if --normalize-html-whitespace is on
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:
These are really equivalent Inline Inline
Compiled:
;
stateless components
Since React v0.14, React allows defining a component as a pure function of its props.
To enable creating a stateless component using react templates, add the rt-stateless
attribute to the template's root element.
Using rt-stateless
generates a stateless functional component instead of a render function.
The resulting function receives props
and context
parameters to be used in the template instead of this.props
.
Sample:
Hello {props.person}
Compiled:
define([ 'react', 'lodash'], function (React, _) { 'use strict'; return function (props, context) { return React.createElement('div', {}, 'Hello ', props.person); };});
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:
Compiled:
;
rt-import and using other components in the template
In many cases, you'd like to use either external code or other components within your template.
To do so, you can use an rt-import
tag that lets you include dependencies in a syntax similar to ES6 imports:
Once included, depVarName will be in scope.
You can only use rt-import 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:
Compiled (ES6 flag):
;;;;;; { return React;}
Compiled (AMD):
;
Compiled (with CommonJS flag):
'use strict';var React = ;var _ = ;var member = member;var alias2 = member;var alias3 = ;var alias4 = default;module { return React;};
deprecated: rt-require
The tag rt-require
is deprecated and replaced with rt-import
.
Its syntax is similar to rt-import
but does not allow default imports:
{utils.toLower(item.name)}
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:
;
Compiled (with jsrt flag):
;
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:
{item}
Compiled (AMD):
;
Compiled (with CommonJS flag):
'use strict';var React = ;var _ = ; { return React;}module { return React;};
Compiled (with ES6 flag):
;; { return React;} { return React;};
Contributing
See the Contributing page.
License
Copyright (c) 2015 Wix. Licensed under the MIT license.