旧网站现代化:如何将RichTextBlock文档链接渲染为按钮?
把Draftail文档链接改成按钮样式的解决方案
嘿,刚好我之前处理过类似的需求,给你一步步拆解怎么实现:
1. 覆盖默认的文档链接渲染模板
Draftail(搭配Wagtail使用时)默认会把文档链接渲染成普通的<a>标签,我们可以通过自定义模板来替换这个逻辑。在你的项目模板目录下新建wagtaildocs/link.html文件,内容如下:
{% load wagtaildocs_tags %} {% if document %} <a href="{% document_url document %}" class="document-button"> <!-- 这里可以根据你的需求添加图标或自定义文本,比如原网站的按钮文案 --> 📄 {{ document.title }} </a> {% endif %}
之后所有通过Draftail插入的文档链接,都会用这个模板渲染,而不是默认的纯文本链接。
2. 用CSS把链接改成按钮样式
接下来给这个<a>标签添加按钮样式,匹配你示例图里的外观:
.document-button { display: inline-block; padding: 8px 16px; background-color: #007bff; /* 可以换成你需要的按钮底色 */ color: #fff; border-radius: 4px; text-decoration: none; font-size: 14px; cursor: pointer; transition: background-color 0.2s; } .document-button:hover { background-color: #0056b3; /* hover时的深色效果 */ text-decoration: none; color: #fff; }
如果你的示例按钮有边框、图标位置等特殊样式,直接调整上面的CSS属性即可。
3. (可选)让编辑器里也预览按钮样式
如果你想在Draftail编辑器里就能看到按钮的样子(而不是纯文本链接),可以在Wagtail的settings.py里配置编辑器的实体装饰器:
WAGTAILADMIN_RICH_TEXT_EDITORS = { 'default': { 'WIDGET': 'wagtail.admin.rich_text.DraftailRichTextArea', 'OPTIONS': { 'features': ['bold', 'italic', 'document-link'], # 保留你需要的编辑器功能 'entity_decorators': { 'DOCUMENT': {'element': 'a', 'props': {'class': 'document-button'}}, }, }, }, }
这样编辑时就能直观看到按钮样式,不用等到前端渲染才确认效果。
额外小技巧
如果旧网站的按钮有下载触发逻辑,比如点击直接下载文档,可以在<a>标签里加download属性:
<a href="{% document_url document %}" class="document-button" download> 📄 {{ document.title }} </a>
内容的提问来源于stack exchange,提问作者SalahAdDin
相关产品推荐
相关产品推荐

