【问题标题】:Django {{message}} not working in JavascriptDjango {{message}} 在 Javascript 中不起作用
【发布时间】:2013-05-06 16:20:22
【问题描述】:

我在 Django 中输出消息时遇到问题。我有 Python,它允许用户输入消息并将其发布到 Google App Engine。我的目标是在 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 + ']);'

如果能在这个问题上提供一些帮助,我将不胜感激。

【问题讨论】:

  • {{ messages.get.message }} 有效吗?在 Django 模板变量查找中不能有括号,但是 Django will automatically call methods
  • 应用程序正在运行..但图像未输出
  • 伙伴谢谢!!我不能相信()是问题所在。但是它确实可以正常工作。 .我用输出对其进行了测试,它打印了消息,但图像仍然没有输出
  • $(document).ready(function(){ var img = document.createElement("img"); img.src = "images/hello.png"; if({{messages.get .message}}== "hello"){ var src = document.getElementById("image1"); src.appendChild(img); )} 这不起作用

标签: javascript django django-templates


【解决方案1】:

试试

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") { ... }

消息周围没有引号会导致语法错误。

【讨论】:

    猜你喜欢
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 2016-04-28
    • 1970-01-01
    • 2020-01-15
    • 2022-01-05
    • 2019-01-07
    • 2019-04-09
    相关资源
    最近更新 更多