6

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!

Arman
  • 1,074
  • 3
  • 20
  • 40

2 Answers2

13

Good ol' safe filter.

{{ link.url|youtube_embed_url|safe }}
Jill-Jênn Vie
  • 1,849
  • 19
  • 22
3

You can also use django-embed-video.

Usage is quite similar:

{% load embed_video_tags %}

{{ link.url|embed:'560x315' }}
Tom Tichý
  • 1,065
  • 1
  • 12
  • 19