我有以下输出:

{'type': 'lead-image', 'value': {'id': 123, 'alt': 'a fish', 'format': 'full-width'}}


我想在html模板上显示该特定图像,我该如何处理?

最佳答案

expand_db_attributes上的wagtail.wagtailimages.rich_text.ImageEmbedHandler方法可完成您要查找的翻译。打包为模板标记(请根据您自己的用例进行适当调整-看起来您那里有Python字典,而不是JSON字符串):

import json
from django.utils.html import escape
from wagtail.wagtailimages.rich_text import ImageEmbedHandler


register = template.Library()

@register.simple_tag
def json_to_image(json_string):
    data = json.loads(json_string)

    # expand_db_attributes expects to receive HTML-escaped attributes,
    # so explicitly escape the alt attribute here (assuming it's not already
    # escaped in your json)
    data['value']['alt'] = escape(data['value']['alt'])

    return ImageEmbedHandler.expand_db_attributes(data['value'], False)

关于python - 从json字符串[Wagtail CMS]在模板上渲染图像,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32097081/

10-11 07:46