【问题标题】:Render Image on a template from a json string [Wagtail CMS]从 json 字符串 [Wagtail CMS] 在模板上渲染图像
【发布时间】:2015-08-19 13:35:03
【问题描述】:

我有以下输出:

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

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

【问题讨论】:

  • 已经发布了一个直接的答案,但我有点好奇这种情况是如何出现的,以及这些数据来自哪里......你在做某种富文本到 StreamField 的转换吗?
  • 嗨,gasman 分享电子邮件结束了您的代码,非常感谢您的输入

标签: python django content-management-system wagtail


【解决方案1】:

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

【讨论】:

  • 如果我没有 alt 属性而我只有 id 和标题怎么办?
猜你喜欢
  • 2021-06-08
  • 2017-11-27
  • 2012-02-17
  • 1970-01-01
  • 1970-01-01
  • 2018-07-29
  • 1970-01-01
  • 1970-01-01
  • 2013-08-11
相关资源
最近更新 更多