Reputation: 1489
How to escape js on a custom template tag?
In my custom_tags.py I have registered a simple tag which simply takes data from firebase in form of array of dictionary. I want to pass this array directly to my JavaScript but doing so gives me error.
my custom_tags.py -
@register.simple_tag
def getMessageData():
message_data = []
data = database.child('ChatMessages').get()
for task in data.each():
message_data.append(task.val())
return dumps(message_data)
in my js -
messageData = JSON.parse("{% getMessageData %}");
This gives me Uncaught SyntaxError: Unexpected token & in JSON at position 2 at JSON.parse (<anonymous>) at (index):23
error.
I tried debugging value by var temp2 = "{% getMessageData %}"
so I found its value to be
So basically I need some way to use escapejs on my custom template tag.. Its easy to do on values passed through rendering but with {% template_tag_name|escapejs %}
gives error as it considers escapejs a part of name.
Upvotes: 0
Views: 47
Reputation: 236
One thing you can try is convert all to the string and then use javascript replaceAll() to convert quot to double inverted commas.
Something like
let getmessageData = [{""hello" : "message""}]
getmessageData = getmessageData[0].replaceAll(""",'"')
console.log(getmessageData);
// Output : "hello" : "message"
Once you get a JSON you can use that in your parse method.
I hope this may help.
Upvotes: 1