I'm trying to use a custom template tag to run a specific function on a variable that I get in JS inside my HTML template.
here is a sample of what I tried :
python template tag
def calculate_km(value, arg):
"""
Calculate the km from the source
"""
args_list = eval(arg)
layer_id = value
return f"layer_id_is:{layer_id}, args_list:{args_list}"
then am using it inside my HTML js block like this :
const args_data = "[" kmlEvent.featureData.id "," kmlEvent.latLng.lat "," kmlEvent.latLng.lng "]";
console.log(`{{single_layer.id|calculate_km: ${args_data} }}`);
The problem here is in adding the JS variable inside the template tag , as you see using args_data
inside the string
that should return syntax for normal Django template
so what is expected is that the console.log
line renders as follows :
{{12|calculate_km:[12,Foo,123,456]}}
But the problem is that it is not reading the value of the variable args_data
and it is being rendered as :
{{12|calculate_km: ${args_data}}}
and of course, that returns an error which is :
django.template.exceptions.TemplateSyntaxError: calculate_km requires 2 arguments, 1 provided
so it seems like not even reading the value of args_data
CodePudding user response:
The Django template tag is rendered on the server side, before serving the HTTP response. What the browser receives in the response is just HTML and JavaScript.
The JavaScript executes on the client side, after all the Django template tags (and other nodes) have already been resolved and rendered.
Unfortunately you cannot pass JavaScript arguments to a Django template tag because the order of execution is incompatible. You'll need to rewrite your template tag as a JavaScript function. Since your code looks like it's being triggered by an event (based off your variable names) switching all the code to execute server-side likely isn't possible.