如何扩展Wagtail图片格式模态框以添加自定义宽度字段?
自定义Wagtail图片格式模态框,添加宽度控制字段
需求背景
内容编辑需要:
- 将图片右对齐,实现文本环绕效果
- 自定义图片宽度,保证在文章中适配缩放
当前Wagtail富文本编辑器的图片格式选择模态框仅支持对齐设置,缺少宽度自定义选项,且不希望通过创建大量组合式图片格式(对齐+宽度的变体)来解决问题。
解决方案
1. 前端扩展图片选择模态框
通过Wagtail的钩子机制,修改图片格式选择模态框,新增宽度输入字段:
- 利用
insert_image钩子注入自定义HTML,添加百分比输入框用于设置宽度 - 监听模态框提交事件,将宽度值与选中的对齐格式一同传递
示例代码(JavaScript):
document.addEventListener('DOMContentLoaded', () => { wagtail.hooks.register('insert_image', (modal) => { const form = modal.body.querySelector('form'); // 新增宽度输入区域 const widthField = document.createElement('div'); widthField.className = 'field'; widthField.innerHTML = ` <label for="custom-image-width">图片宽度(%)</label> <input type="number" id="custom-image-width" name="custom-width" min="10" max="100" value="100"> `; form.appendChild(widthField); // 提交时把宽度值附加到图片属性 const submitBtn = modal.body.querySelector('button[type="submit"]'); submitBtn.addEventListener('click', (e) => { const width = document.getElementById('custom-image-width').value; // 将宽度值存入模态框的提交数据中 modal.options.width = width; }); }); });
2. 后端处理富文本渲染逻辑
自定义Wagtail的图片嵌入处理器,解析并应用宽度与对齐属性:
- 继承默认的图片嵌入处理器,扩展
expand_db_attributes方法 - 读取前端传入的宽度值,生成对应的内联样式,结合对齐设置实现文本环绕
示例代码(Python):
from wagtail.core.rich_text import RichText from wagtail.images.rich_text import ImageEmbedHandler class CustomImageHandler(ImageEmbedHandler): @classmethod def expand_db_attributes(cls, attrs): base_html = super().expand_db_attributes(attrs) width = attrs.get('custom-width', '100') format_type = attrs.get('format', '') # 针对右对齐图片添加宽度和浮动样式 if 'right' in format_type: style = f'width: {width}%; float: right; margin: 0 0 1rem 1rem;' base_html = base_html.replace('<img', f'<img style="{style}"') return base_html # 注册自定义处理器 RichText.register_handler('image', CustomImageHandler)
3. 前端样式适配
添加CSS确保图片缩放与文本环绕的兼容性:
.rich-text img[style*="float:right"] { max-width: 100%; height: auto; object-fit: cover; }
参考界面
参考WordPress Gutenberg编辑器的图片设置界面,将对齐与宽度拆分为独立控制项,避免生成过多格式变体:
内容的提问来源于stack exchange,提问作者Brylie Christopher Oxley
相关产品推荐
相关产品推荐

