如何在Django聚合订阅框架中添加不被转义的HTML代码?
问题背景
使用Django syndication feed框架生成RSS时,在item_description方法中拼接HTML链接后,输出的RSS内容里HTML标签被自动转义,无法正常渲染链接。
解决方案
要让HTML内容不被转义,只需将返回的描述内容用django.utils.safestring.mark_safe()方法包裹,Django会自动将其包装在CDATA块中,避免转义。
修改后的代码
from django.contrib.syndication.views import Feed from django.urls import reverse from django.utils.safestring import mark_safe from policebeat.models import NewsItem class LatestEntriesFeed(Feed): title = "Police beat site news" link = "/sitenews/" description = "Updates on changes and additions to police beat central." def items(self): return NewsItem.objects.order_by('-pub_date')[:5] def item_title(self, item): return item.title def item_description(self, item): description = item.article_description description += "<a href='test.com'>Click to my site</a>" return mark_safe(description) # item_link is only needed if NewsItem has no get_absolute_url method. def item_link(self, item): return reverse('news-item', args=[item.pk])
原理说明
mark_safe()会标记字符串为“安全”,告诉Django不需要对其进行HTML转义。- Django的syndication框架检测到安全字符串时,会自动将其包裹在
<![CDATA[...]]>块中,符合XML/RSS的规范,确保HTML内容能被阅读器正确解析。
验证结果
修改后生成的RSS内容会变成:
<description><![CDATA[...原有描述内容...<a href='test.com'>Click to my site</a>]]></description>
内容的提问来源于stack exchange,提问作者Yarin Zhang
相关产品推荐
相关产品推荐

