Home > Mobile >  Django / How to evaluate a django variable inside a bracket expression?
Django / How to evaluate a django variable inside a bracket expression?

Time:05-07

In my html file I need to define a variable for a js file.

<script>
 var gltf_home = "{% static '/3d/ {{ scene.GltfFileToLoad }} ' %}";
</script>

which gives as an output :

/static/3d/{{ scene.GltfFileToLoad }}

instead of

/static/3d/00-world.glb

And this alternative

var gltf_home = "{% static '/3d/' {{ scene.GltfFileToLoad }} %}";

gives

/static/3d/

What would be the correct way to do it ?

CodePudding user response:

You can work with the |add template filter [Django-doc]:

var gltf_home = "{% static '/3d/'|add:scene.GltfFileToLoad %}";

But I would advise not to do this: perform the logic in the view, and work with the |json_script template filter [Django-doc], this will properly encode the data in a JSON blob, and thus prevents escaping, etc.

  • Related