मैंने अपने कस्टम 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>
हालांकि, जब मैं ब्राउज़र में लिंक पृष्ठ को देखने मैं स्ट्रिंग के रूप में एचटीएमएल कोड देखें:
किसी भी विचार कैसे HTML कोड के रूप में व्याख्या करने के लिए youtube_embed_url विधि का परिणाम बनाएं, स्ट्रिंग नहीं? अग्रिम धन्यवाद, दोस्तों!
हम एक वास्तविक जवाब के लिए इंतजार, फिर भी कृपया http://stackoverflow.com/questions/4848611/django-rendering-a-template-variable- पर एक नज़र डालें:
प्रयोग काफी समान है के रूप में एचटीएमएल – kush
@ अरमान, उपयोगी कोड के लिए धन्यवाद। –
यह एक अच्छा Django स्निपेट बना देगा ... – nicorellius