簡體   English   中英

Django:將 HTML 字符串傳遞給模板

[英]Django: Passing HTML string to template

我在嘗試顯示在 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 字符串:

 <div id="modal_book_name">Clockwork orange</div>
 <div id="modal_book_genre">Dystopian fiction</div>
 <br>
 <div id="modal_book_desc">yadayadayadayada</div>

現在,由於我不希望內容出現在我的 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 一切似乎都很好:

<div id="modal_book_name">Clockwork orange</div><div id="modal_book_genre">Dystopian fiction</div><br><div id="modal_book_desc">yadayadayadayada</div>

不幸的是,當我打開頁面時,modal_info div 是空的。 當我打開瀏覽器的開發人員工具並檢查該 div 的 html 時,我看到的是:

 <div id="modal_info">
      "<div id="modal_book_name">Clockwork orange</div><div id="modal_book_genre">Dystopian fiction</div><br><div id="modal_book_desc">yadayadayadayada</div>"
 </div>

問題在於那些引號。 他們是怎么出現在那里的? 我怎樣才能擺脫它們,為什么它們首先放在那里?

提前致謝。 如果有什么不清楚的,請隨時提問,我會澄清的。

更新:嗯,事實證明 modal_info div 畢竟不是空的..文本只是與背景顏色相同。 抱歉,那是我的愚蠢。 但問題仍然存在。 我應該看到的地方:

 Clockwork Orange
 Dystopian fiction

 yadayadayadayada

我看到的是文字 html:

 <div id="modal_book_name">Clockwork orange</div><div id="modal_book_genre">Dystopian fiction</div><br><div id="modal_book_desc">yadayadayadayada</div>

我嘗試使用 parseHTML 函數將字符串解析為 HTML:

  var book_desc = $.parseHTML(books_description[book_name]);
  $("#modal_info").html(book_desc);

但結果是一樣的。 知道如何讓瀏覽器將字符串解釋為 html 代碼而不是文字字符串

問題解決了。 沒有我想象的那么戲劇化。 碰巧 django 正在將諸如 '<' 和 '>' 之類的 html 標記轉換為 '&lt' 和 '&gt'

這導致頁面上的輸出正確,但無法創建相應的 DOM 對象。

修復:

 {% autoescape off %}
    {% for book, book_desc in bd.items %}
       books_description["{{ book }}"] = "{{ book_desc|escapenewline }}"
    {% endfor %}
 {% endautoescape %}

花了我一段時間。 如果有人遇到類似的問題,這里有一些關於自動轉義的信息

自動轉義過濾器

如果有人因為最近的 django 版本登陸這里,請使用: {{ your_context_entry|safe }}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM