Skip to content

Commit d7e0faa

Browse files
committed
Merge pull request facebookarchive#9 from andreypopp/master
Add JSXTransformer.transform_string() method to transform strings
2 parents eaadf31 + e555295 commit d7e0faa

File tree

2 files changed

+28
-9
lines changed

2 files changed

+28
-9
lines changed

README.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,14 @@ for jsx_path, js_path in my_paths:
3434
jsx.transform('path/to/input/file.jsx', 'path/to/output/file.js')
3535
```
3636

37+
You can also use ``transform_string(jsx)`` method to transform strings:
38+
39+
```python
40+
from react import jsx
41+
transformer = jsx.JSXTransformer()
42+
js = transformer.transform_string(jsx)
43+
```
44+
3745
**Django**: PyReact includes a JSX compiler for [django-pipeline](https://github.com/cyberdelia/django-pipeline). It has been tested with django-pipeline 1.3.20, but may work with other versions too. Add it to your project's pipeline settings like this:
3846

3947
```python

react/jsx.py

Lines changed: 20 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -17,24 +17,35 @@
1717

1818

1919
class JSXTransformer(object):
20+
2021
def __init__(self):
2122
path = react.source.path_for('JSXTransformer.js')
2223
with open(path, 'rU') as f:
2324
self.context = execjs.compile(f.read())
2425

25-
def transform(self, jsx_path, js_path=None):
26+
def transform_string(self, jsx):
27+
""" Transform ``jsx`` JSX string into javascript
28+
29+
:param jsx: JSX source code
30+
:type jsx: basestring
31+
:return: compiled JS code
32+
:rtype: str
33+
"""
2634
try:
27-
with open(jsx_path, 'rU') as i:
28-
result = self.context.call(
29-
'JSXTransformer.transform', i.read())
30-
js = result['code']
31-
if js_path:
32-
with open(js_path, 'wb') as o:
33-
o.write(js.encode('utf8'))
34-
return js
35+
result = self.context.call('JSXTransformer.transform', jsx)
36+
js = result['code']
37+
return js
3538
except execjs.ProgramError as e:
3639
raise TransformError(e.message[7:])
3740

41+
def transform(self, jsx_path, js_path=None):
42+
with open(jsx_path, 'rU') as i:
43+
js = self.transform_string(i.read())
44+
if js_path:
45+
with open(js_path, 'wb') as o:
46+
o.write(js.encode('utf8'))
47+
return js
48+
3849

3950
class TransformError(Exception):
4051
def __init__(self, message):

0 commit comments

Comments
 (0)