2013-05-12 54 views
0

我在Django中輸出消息時出現問題。我有Python,它允許用戶輸入消息並將其發佈到Google App Engine。我打算做的是在Javascript中使用比較字符串輸出正確的圖像。Django {{message}}不能在Javascript中工作

我在Javascript中使用以下內容。

var img = document.createElement("img"); 
img.src = "images/150.png"; 
if ({{messages.get().message}} == "hello"){ 
    var src = document.getElementById("image1"); 
    src.appendChild(img); 
} 

我不明白爲什麼messages.get().message不起作用。由於某種原因,它給了我一個解析錯誤。用來張貼在JSON消息的Python代碼如下:

endef getJSONMessages(callback): 
messages = db.GqlQuery("SELECT * FROM Message ORDER BY timestamp DESC LIMIT 1") 
strlist = "" 
for message in messages: 
    if len(strlist)>0: 
     strlist += ',' + message.asJSONString() 
    else: 
     strlist = message.asJSONString()     
if callback=='': 
    return '[' + strlist + ']' 
else:  
    return callback+'([' + strlist + ']);' 

我將是一些幫助,這個問題非常感謝。

+0

「{{messages.get.message}}」有效嗎?在Django模板變量查找中不能有括號,但Django [將自動調用方法](https://docs.djangoproject.com/en/1.5/topics/templates/#variables)。 – andrewdotn 2013-05-12 14:37:31

+0

該應用程序現在運行..但圖像不輸出 – user2336427 2013-05-12 14:41:08

+0

伴侶謝謝!我不能beleive()是問題..但它確實工作。 。我測試它與輸出,它打印消息,但圖像仍然沒有把輸出 – user2336427 2013-05-12 14:45:30

回答

0

嘗試

var img = document.createElement("img"); 
img.src = "images/150.png"; 
if ("{{messages.get.message|escapejs}}" == "hello"){ 
    var src = document.getElementById("image1"); 
    src.appendChild(img); 
} 

沒有必要對 「messages.get()」 中的模板。 「messages.get」wii做。

如果使用

if(messages.get.message == "hello") { ... } 

將有消息,這將導致語法錯誤周圍沒有引號。