使用Jinja模板/Flask實現帶有加粗修飾的嵌套HTML段落渲染
P粉170438285
P粉170438285 2024-03-22 13:59:22
0
1
450

我正在尋找創建一個函數,該函數可以從句子中刪除單詞,然後用從字典API搜尋中獲取的其他單字替換已刪除的單字。

非常簡單,這是一個檢查句子中的單字是否屬於被刪除單字清單的函數,如果是,則用替代單字替換,如果不是,則將原始單字新增到新字串中。沒有問題,

我需要幫助的是,如果我使用F字串並添加文字修飾符以在HTML標記中解釋,這樣做的方式是正確的嗎?我只想加粗替換的文字

if word in removed_words:
               print("our word for the dictionary is", word)  
               res =  dictionary.meaning(word.capitalize())

               if res != None:
              
                   if res.get('Noun'):
                      print("our definition is", "---> ", res['Noun'][0], " <----")
                      remaining_words.append(f"""{res['Noun'][0]}""")

                   elif res.get('Verb'):
                        print("our definition is", "---> ", res['Verb'][0], " <----")
                        remaining_words.append(f"""{res['Verb'][0]}""")

               else:
                    remaining_words.append(f"""{r.word()}""")
             
           else:
                remaining_words.append(word)

當我在瀏覽器中檢查HTML標記時,包含新字串的段落元素被正確編譯,例如

<p>This is the new sentence with the <b>replaced word</b> and the other words</p>

然而問題是,最終的標記中隱含了<b>,但沒有被渲染出來。 我在這裡漏掉了什麼嗎?

在渲染過程中,段落被調用到的Flask模板標記如下,包含問題[0]的<p>是我討論的新渲染字串值。

h3 class="header3 head4">{{heading}}

<p id="question">{{question[0]}}</p>

<button id="showanswer">Show the Answer</button>
<p id="answer">{{question[1]}}</p>

<form  id="submitanswer" method="post", action="/quiz/processanswer">
<input id="useranswer" type="text" name="answer" placeholder="Enter your answer">
<input id="hiddenanswer" name="hiddenanswer" type="text" value="{{question[1]}}" 
 id="hiddenanswer">
 <button id="answerSubmit">Submit</button>
 </form>

感謝您的幫忙!

P粉170438285
P粉170438285

全部回覆(1)
P粉087074897

預設情況下,Jinga會自動轉義變數中的字符,如 >、<(當使用{{question[0]}}時)。

如果你對question[0]的建構方式有信心,你可以透過將<p id="question">{{question[0]}}</p>改為<p id="question">{{question[0] | safe }}</p>來繞過這個自動轉義。

更多資訊請參考:https://jinja.palletsprojects.com/en/3.0.x/templates/#html-escaping

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!