Spatial Digger
Spatial Digger

Reputation: 1993

Send a Django variable to javascript

I'm trying to access a Django placeholder, which is an array from the database, in a javascript script for use within three.js

I have the coord_x, coord_y and coord_z variables in views.py which comes from the database through:

cur.execute("""SELECT x FROM pc_processing.basesample""")
coord_x = cur.fetchall()
cur.execute("""SELECT y FROM pc_processing.basesample""")
coord_y = cur.fetchall()
cur.execute("""SELECT z FROM pc_processing.basesample """)
coord_z = cur.fetchall()

In my templates html (random testing numbers commented out, good for testing):

...
for (var i = 0 ; i < numpoints ; i++) {

    var x = {{coord_x}};
    var y = {{coord_x}};
    var z = {{coord_x}};

    // var x = Math.random() * (0 - 1) + 1
    // var z = Math.random() * (0 - 1) + 1
    // var y = Math.random() * (0 - 1) + 1

    var dotGeometry = new THREE.Geometry();
    dots.push(dotGeometry);
    dotGeometry.vertices.push(new THREE.Vector3(x, y, z));
    var dotMaterial = new THREE.PointsMaterial( { size: 3, sizeAttenuation: false, color: 0xFF0000 });
    var dot = new THREE.Points( dotGeometry, dotMaterial);
    scene.add(dot);
}
...

I'm guessing I need to somehow loop through the x,y,z variables?

Upvotes: 1

Views: 303

Answers (1)

ruddra
ruddra

Reputation: 51978

You can try like this:

send the variable through context like this in views.py:

context = { 'coord_x': 20, 'coord_y': 10, 'coord_z': 30}
return render(request, 'template.html', context)

And in the template attach the variables to window object:

<script>
window.x = "{{coord_x}}"
window.y = "{{coord_x}}"
window.z = "{{coord_x}}"
</script>

And use this in your JS file. if the variables are list then you have to loop through them:

var currX = x[i];
var currY = y[i];
var currZ = z[i];

dotGeometry.vertices.push(new THREE.Vector3(currX, currY, currZ));

Even better approach for this is to send these variables not as list, but dictionary. Like this in views.py:

context = { 'coordinates': [{'x':1, 'y':2, 'z':3}, {'x':1, 'y':2, 'z':4}] }
return render(request, 'template.html', context)

attach them in JS:

<script>
window.coordinates = "{{ coordinates }}";
</script>

and use it js like this:

coordinates.forEach(function(i){
...
dotGeometry.vertices.push(new THREE.Vector3(i.x, i.y, i.z));
...
}

Upvotes: 2

Related Questions