i need get context in react using django but i cant do it
this is my code in my jsx
<h1>{{titulo}}</h1>
<h2>{{ejemplo}}</h2>
in my template:
{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body >
<div id="app"></div>
<script type="text/javascript" src="{% static 'bundle.js' %}"></script>
</body>
</html>
in my view py:
def registro (request,giro):
reg = 'Registro Normal'
if giro==1:
reg='Registro Especial'
context = {
'ejemplo':'tests',
'titulo':reg
}
return render(request,'home/registro.html',context)
but does not render and wild error appeared :(
Uncaught ReferenceError: titulo is not defined
The Django context is only when the template is rendered on the server. React uses Javascript which means it's rendered on the browser. If you want to use Django variables in your React app, you will need to set those variables in Javascript (making sure to do so before bundle.js
is imported).
So your template might look something like this:
{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body >
<div id="app"></div>
<script type="text/javascript">
/* Put your context vars here. I recommend putting them under
a variable to avoid naming conflicts.
*/
var context = {
titulo: '{{titulo}}',
ejemplo: '{{ejemplo}}'
};
</script>
<script type="text/javascript" src="{% static 'bundle.js' %}"></script>
</body>
</html>
Then in React you can reference context.variable
to get the value you need.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With