Home > Software design >  Use Javascript variable in Django Tempate
Use Javascript variable in Django Tempate

Time:07-18

Before getting into the question, I know that there are a lot of similar questions on Stack Overflow, but from what I've seen none has produced an answer I can use -- please correct me if I'm wrong.

I have a JavaScript variable that looks like this (this is in a <script> tag).

var html = '<img src = "{% static "img/chesspieces/wikipedia/(I guess this is the part I'm not sure about)" %}"'

I have another JavaScript variable called piece that I would like to inject like this {{piece}}, but can't since it's a JavaScript variable, and not a Django variable.

A lot of answers to similar questions seem to recommend making a view and calling it every time I want to access the piece variable, but I don't think that has any chance of working in my situation, as it would lead to the Too Many Requests error.

CodePudding user response:

Rather than doing it dynamically, can't you set it up in advance? There's not a huge overhead in doing static lookups.

var html = ""
var pieceDict = new Object();
pieceDict['king'] ='<img src = "{% static "img/chesspieces/wikipedia/king.gif" %}"'>
pieceDict['queen'] = '<img src = "{% static "img/chesspieces/wikipedia/queen.gif" %}"'>

...    
piece = "king"
html = pieceDict[piece]
  • Related