Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how get context react using django

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

like image 392
Jesus Juarez Avatar asked Dec 11 '22 11:12

Jesus Juarez


1 Answers

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.

like image 77
Jessie Avatar answered Dec 18 '22 07:12

Jessie