我通过实现自定义模板标签解决了这个问题。这可能是一个快速且有点肮脏的解决方案(自定义提供程序可能是官方的方式),但它有效,这对我来说已经足够了。
用户插入常规 URL。如果 URL 用于 Youtube 或 Vimeo,则自定义模板标签会处理它。否则,模板使用默认的 Wagtail 提供程序。
project/templatetags/custom_template_tags.py:
import re
from django import template
register = template.Library()
@register.filter
def get_embed_url_with_parameters(url):
if 'youtube.com' in url or 'youtu.be' in url:
regex = r"(?:https:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?(.+)" # Get video id from URL
embed_url = re.sub(regex, r"https://www.youtube.com/embed/\1", url) # Append video id to desired URL
embed_url_with_parameters = embed_url + '?rel=0' # Add additional parameters
return embed_url_with_parameters
elif 'vimeo.com' in url:
embed_url = url.replace('vimeo.com', 'player.vimeo.com/video')
embed_url_with_parameters = embed_url + '?loop=0&title=0&byline=0&portrait=0'
return embed_url_with_parameters
else:
return None
/project/templates/video_embed.htm:
{% load wagtailcore_tags %}
{% load wagtailembeds_tags %}
{% load custom_template_filters %}
{% with value.embed.url as regular_url %}
{% with regular_url|get_embed_url_with_parameters as embed_url %}
<div class="container">
<div class="block-description cvast-embed cvast-spacer-top">
<div align="center">
<h5>{{ value.title }}</h5>
{% if embed_url is None %}
{% embed regular_url %}
{% else %}
<iframe src="{{ embed_url }}" frameborder="0" allowfullscreen></iframe>
{% endif %}
</div>
</div>
</div>
{% endwith %}
{% endwith %}
project/models.py:
from wagtail.wagtailcore.models import Page
from wagtail.wagtailcore.blocks import StructBlock
from wagtail.wagtailembeds.blocks import EmbedBlock
from wagtail.wagtailadmin.edit_handlers import FieldPanel
class EmbedVideoBlock(StructBlock):
embed = EmbedBlock()
class Meta:
template = "blocks/embed_video_block.htm"
class YourPage(Page):
video = EmbedVideoBlock()
content_panels = Page.content_panels + [
FieldPanel('video'),
]