从json字符串在模板上渲染图像[Wagtail CMS]

时间:2015-08-19 13:35:04

标签: python django content-management-system wagtail

我有以下输出:

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

我想在我的html模板上显示该特定图像,我该怎么做呢?

1 个答案:

答案 0 :(得分:1)

expand_db_attributes上的wagtail.wagtailimages.rich_text.ImageEmbedHandler方法执行您要查找的翻译。打包为模板标签(请根据您自己的用例进行调整 - 看起来您有一个Python dict,而不是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)