2012-08-06 16 views
6

मैंने अपने कस्टम Django फ़िल्टर youtube_embed_url को templatetags/custom_filters.py में परिभाषित किया है। यह एक यूट्यूब यूआरएल लेता है और वीडियो के लिए एम्बेड कोड है जो स्ट्रिंग देता है। templatetags/custom_filters.py के लिए कोड के नीचे है:Django: यूट्यूब यूआरएल को HTML एम्बेड कोड में परिवर्तित करना

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> 

हालांकि, जब मैं ब्राउज़र में लिंक पृष्ठ को देखने मैं स्ट्रिंग के रूप में एचटीएमएल कोड देखें:

enter image description here

किसी भी विचार कैसे HTML कोड के रूप में व्याख्या करने के लिए youtube_embed_url विधि का परिणाम बनाएं, स्ट्रिंग नहीं? अग्रिम धन्यवाद, दोस्तों!

+0

हम एक वास्तविक जवाब के लिए इंतजार, फिर भी कृपया http://stackoverflow.com/questions/4848611/django-rendering-a-template-variable- पर एक नज़र डालें:

प्रयोग काफी समान है के रूप में एचटीएमएल – kush

+0

@ अरमान, उपयोगी कोड के लिए धन्यवाद। –

+0

यह एक अच्छा Django स्निपेट बना देगा ... – nicorellius

उत्तर

3

तुम भी django-embed-video उपयोग कर सकते हैं।

{% load embed_video_tags %} 

{{ link.url|embed:'560x315' }} 
संबंधित मुद्दे