Utkarsh Tyagi
Utkarsh Tyagi

Reputation: 1489

How to import data from custom template tag to javascript? Django

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 enter image description here

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

Answers (1)

Sanjeev_gupta2812
Sanjeev_gupta2812

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  = [{"&quot;hello&quot; : &quot;message&quot;"}]
getmessageData = getmessageData[0].replaceAll("&quot;",'"')
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

Related Questions