当Python代码放在​​Django模板中时,语法错误 [英] Syntax error whenever I put Python code inside a Django template

查看:95
本文介绍了当Python代码放在​​Django模板中时,语法错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  {%嵌入嵌入%} $ b我想在Django模板中执行以下操作: $ b {%embed2 = embed.replace(&,<)%} 
{{embed2}}< br />
{%endfor%}

但是,我总是得到一个无效的块或一些语法错误当我做这样的事情(我的意思是循环中的{%%}代码)。 Python没有{}表示范围,所以我认为这可能是我的问题?我的格式化我的代码错误?



编辑:确切的错误是:无效的块标签:'embed2' / p>

编辑2:由于有人说我在做什么是Django模板不支持的,我重写了代码,将逻辑放在视图中。我现在有:

  embed_list = [] 
嵌入嵌入:
embed_list [len(embed_list ):] = [embed.replace(&,<)] #this是第35行
返回render_to_response(scanvideos.html,{
embed_list:embed_list
})

但是,我现在得到一个错误: noneType'object is not callableon line 35

解决方案

而不是使用片段分配增加列表



embed_list [len(embed_list):] = [foo]



你应该可以做



embed_list.append(foo)



但是,您真的应该尝试使用库函数来转义html,而不是自己执行。



NoneType错误听起来像嵌入.replace在某个时候是None,只有当你的列表不是一个字符串列表时才有意义 - 你可能希望用一些断言或者一些si milar。


I'm trying to do the following in my Django template:

    {% for embed in embeds %}
           {% embed2 = embed.replace("&lt;", "<") %}
           {{embed2}}<br />
    {% endfor %}

However, I always get an invalid block or some syntax error when I do anything like that (by that I mean {% %} code inside a loop). Python doesn't have {} to signify "scope" so I think this might be my problem? Am I formatting my code wrong?

Edit: the exact error is: Invalid block tag: 'embed2'

Edit2: Since someone said what I'm doing is not supported by Django templates, I rewrote the code, putting the logic in the view. I now have:

embed_list = []
for embed in embeds:
    embed_list[len(embed_list):] = [embed.replace("&lt;", "<")] #this is line 35
return render_to_response("scanvideos.html", {
    "embed_list" :embed_list
})

However, I now get an error: 'NoneType' object is not callable" on line 35.

解决方案

Instead of using a slice assignment to grow a list

embed_list[len(embed_list):] = [foo]

you should probably just do

embed_list.append(foo)

But really you should try unescaping html with a library function rather than doing it yourself.

That NoneType error sounds like embed.replace is None at some point, which only makes sense if your list is not a list of strings - you might want to double-check that with some asserts or something similar.

这篇关于当Python代码放在​​Django模板中时,语法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆