Block tag are invalid
I wrote block tag, when I try to cause it in template I got an error:
Invalid block tag: 'endyoutube'
My tag
from django import template
register = template.Library()
@register.tag
def youtube(parser, token):
link = parser.parse(('endyoutube', ))
iframe = """<iframe width="640" height="510" src="%s" frameborder="0"
allowfullscreen></iframe>""" % link
return YoutubeNode(iframe)
class YoutubeNode(template.Node):
def __init__(self, iframe):
self.iframe = iframe
def render(self, context):
video = self.iframe.render(context)
return video
te开发者_如何转开发mplate
{% load customtags %}
{% youtube %}
http://www.youtube.com/watch?v=yZt1qXnOOqU
{% endyoutube %}
What is wrong in my tag? How could I fix it?
I got it. First mistake - I didn't use delete_first_token(), it's deleting closing tag from tokens, it was the cause of the error. Second mistake - this is impossible insert a parsed data into a string in function, because it's not a string, but class 'django.template.debug.DebugNodeList'. This object requires render() method to be a string caused in Node class instance. And the last one - youtube link for embed and for watch are different.
Workable tag
class YoutubeNode(template.Node):
def __init__(self, parsed_link):
self.parsed_link = parsed_link
def render(self, context):
del_it = re.compile('&feature=related')
replace_it = re.compile('watch\?v=')
link = self.parsed_link.render(context)
link = del_it.sub('', link)
link = replace_it.sub('embed/', link)
video = """<p><iframe width="550" height="438" src="%s"
frameborder="0" allowfullscreen></iframe></p>""" % link
return video
@register.tag
def youtube(parser, token):
parsed_link = parser.parse(('endyoutube', ))
# first token it's closing tag. delete_first_token just delete it - del self.tokens[0];)
parser.delete_first_token()
return YoutubeNode(parsed_link)
精彩评论