Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: converting Youtube URL to HTML embed code

I defined my custom Django filter youtube_embed_url in templatetags/custom_filters.py. It takes an Youtube url and returns the string which is embed code for the video. The code for templatetags/custom_filters.py is 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 in link_page.html page. Here is the relevant portion of link_page.html:

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

However, when I view the link page in browser I see the HTML code as the string:

enter image description here

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

like image 303
Arman Avatar asked Aug 06 '12 23:08

Arman


2 Answers

Good ol' safe filter.

{{ link.url|youtube_embed_url|safe }}
like image 127
Jill-Jênn Vie Avatar answered Nov 11 '22 15:11

Jill-Jênn Vie


You can also use django-embed-video.

Usage is quite similar:

{% load embed_video_tags %}

{{ link.url|embed:'560x315' }}
like image 3
Tom Tichý Avatar answered Nov 11 '22 13:11

Tom Tichý