Arman
Arman

Reputation: 1084

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!

Upvotes: 6

Views: 5404

Answers (2)

Tom Tich&#253;
Tom Tich&#253;

Reputation: 1065

You can also use django-embed-video.

Usage is quite similar:

{% load embed_video_tags %}

{{ link.url|embed:'560x315' }}

Upvotes: 3

Jill-J&#234;nn Vie
Jill-J&#234;nn Vie

Reputation: 1841

Good ol' safe filter.

{{ link.url|youtube_embed_url|safe }}

Upvotes: 13

Related Questions