我在templatetags / custom_filters.py中定义了自定义Django过滤器youtube_embed_url。它需要一个Youtube网址并返回嵌入视频代码的字符串。 templatetags / custom_filters.py的代码如下:
from django import template
from django.conf import settings
register = template.Library()
import re
@register.filter(name='youtube_embed_url')
# converts youtube URL into embed HTML
# value is url
def youtube_embed_url(value):
match = re.search(r'^(http|https)\:\/\/www\.youtube\.com\/watch\?v\=(\w*)(\&(.*))?$', value)
if match:
embed_url = 'http://www.youtube.com/embed/%s' %(match.group(2))
res = "<iframe width=\"560\" height=\"315\" src=\"%s\" frameborder=\"0\" allowfullscreen></iframe>" %(embed_url)
return res
return ''
youtube_embed_url.is_safe = True
然后我在link_page.html页面中使用此过滤器。以下是link_page.html的相关部分:
<div>
{{ link.url|youtube_embed_url }}
</div>
但是,当我在浏览器中查看链接页面时,我将HTML代码视为字符串:
知道如何将youtube_embed_url方法的结果解释为HTML代码,而不是字符串?提前谢谢,伙计们!