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

Issue

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/%7B%7B%20scene.GltfFileToLoad%20%7D%7D

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 ?

Solution

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.

Answered By – Willem Van Onsem

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published