我有一個變量text = "replace some word"在一個視圖中。我想替換'some'為粗體。像這樣:"replace **some** word"如何在 Django 模板中處理該變量?
2 回答

慕妹3146593
TA貢獻1820條經驗 獲得超9個贊
顯然,**不要在模板中使用粗體字符串,您將很難嘗試在模板中用適當的開始和結束標記替換這些標記,例如通過自定義過濾器。但是,您可以通過在視圖中應用必要的 HTML 并將其標記為安全來將其設為粗體:
# views.py
from django.utils.safestring import mark_safe
# in your view
# ...
text = "replace some word"
# add the appropriate html tags
text = text.replace('some', '<strong>some</strong>')
# now you have to mark it as safe so the tags will be rendered as tags
text = mark_safe(text)
# ...
return render(reqest, template, {.., 'text': text, ...})
現在你可以像模板中的普通變量一樣使用它 {{ text }}
添加回答
舉報
0/150
提交
取消