我在尝试显示在django视图上创建的代码的html块时遇到问题。 这是发生了什么。Django:将HTML字符串传递给模板
在我看来,我试图传递给模板一堆书描述,我会根据用户操作隐藏/显示。这些描述存储在服务器上的html文件中。
def my_view()
#loop through the list of books, read their corresponding a html file, and parse it to fill in the book details
#code, code, code...
#take the resulting string, append it on books description array, log it and send it to template
logger.debug(books_description["Clockwork orange"])
return render_to_response("my_template.html", {'bd': books_description}, context_thingy)
到目前为止这么好。我的日志显示HTML字符串正是因为它应该:现在
,因为我不想要的内容在我的html代码铺设约,我读的书描述成像这样一个javascript变量:
books_description = {};
{% for book, book_desc in bd.items %}
books_description["{{ book }}"] = "{{ book_desc|escapenewline }}"
{% endfor %}
escapenewline是一个过滤器,它在每行的末尾放置一个\以确保javascript能够正确解释整个字符串内容。
最后,当用户想要查看某本书上的描述时,他只需点击它,模式就会显示出书的描述。为了这个,我有:
console.log(books_description[book_name]);
$("#modal_info").html(books_description[book_name]);
再次,一切似乎很动听本的console.log:
不幸的是,当我打开网页的modal_info格是空的。当我打开浏览器的开发者工具和检查HTML的该div这里是我所看到的:
"
的问题是在这些引号。他们是如何出现在那里的?我怎么能摆脱他们,为什么他们放在那里呢?
在此先感谢。如果有什么不清楚的地方,随时提问,我会澄清它。
UPDATE:嗯,原来,modal_info DIV不毕竟..文本只有相同的颜色作为背景空。道歉,这是我的愚蠢。但问题依然存在。在那里我应该看到:
Clockwork Orange
Dystopian fiction
yadayadayadayada
我看,而不是字面的html:
我试图解析字符串与parseHTML功能HTML:
var book_desc = $.parseHTML(books_description[book_name]);
$("#modal_info").html(book_desc);
但结果是相同的。任何想法如何让浏览器将该字符串解释为html代码而不是字符串