Django: Convert Youtube URL to HTML

I defined my own youtube_embed_url Django filter in templatetags / custom_filters.py. It takes the URL of Youtube and returns a string, which is the code for the video. The code templatetags / custom_filters.py is shown below:

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 

Then I use this filter on the link_page.html page. Here is the relevant part of link_page.html:

 <div> {{ link.url|youtube_embed_url }} </div> 

However, when I look at the link page in a browser, I see the HTML code as a string:

enter image description here

Any idea how to get the result of the youtube_embed_url method to be interpreted as HTML code, not a string? Thanks in advance guys!

+6
source share
2 answers

Good ol safe filter .

 {{ link.url|youtube_embed_url|safe }} 
+11
source

You can also use django-embed-video .

Usage is pretty similar:

 {% load embed_video_tags %} {{ link.url|embed:'560x315' }} 
+3
source

Source: https://habr.com/ru/post/922251/


All Articles