I am working on a project in which i am using the react js with Webapp2. I am trying to use jinja2 in react component. It compiles successfully but when i actually load the webpage. It gives error in console. Here is the handler code in which i am simply rendering the page and passing some values.
class Login(BaseHandler, Handler):
def get(self):
jinja_environment = self.jinja_environment
template = jinja_environment.get_template("/index.html")
self.response.out.write(template.render({'a': "aa", 'b': "bb"}))
I have tried following two methods for using jinja2 in React.
Method 1:
var Main = (props) => {
return (
<div>
{{a}} // directly use the jinja2 variable.
<Nav/>
<div className="row">
<div className="columns medium-6 large-4 small-centered">
{props.children}
</div>
</div>
</div>
);
};
This method gives following error on console:
Method 2: I use this method usually in Javascript and it works fine there. It do not show the value but page renders successfully.
var Main = (props) => {
var a = '{{a}}';
return (
<div>
{a}
<Nav/>
<div className="row">
<div className="columns medium-6 large-4 small-centered">
{props.children}
</div>
</div>
</div>
);
};
Here is the page view.
Please help where i am doing mistake.
Flask preprocesses only the markup in the template file. It will never do included static files. So have this script in your template before the react loading script, so that your react app can access the variable x.
In views
import json
....
template.render({'some_details': json.dumps({'foo':'bar'})})
return render_template('login.html', some_details=json.dumps({"foo":"bar}))
In template
<script type="text/javascript">
var x = {{ some_details|safe }};
console.log("x and x.foo", x, x.foo)
</script>
<script src="/static/react_bundle.js"></script>