【问题标题】:How to output just html image tag when I have text and html in django template output?当我在 django 模板输出中有文本和 html 时,如何仅输出 html 图像标签?
【发布时间】:2012-07-11 20:43:04
【问题描述】:

我用这个来输出,

{{ movie.img }}

我得到的输出应该是这样的,

u'<img src="//upload.wikimedia.org/wikipedia/en/thumb/8/8a/Dark_Knight.jpg/220px-Dark_Knight.jpg" alt="" height="327" width="220" >\nTheatrical release poster'

如何只输出 html 图片部分?我不希望剧场版海报出现在输出中。

【问题讨论】:

    标签: html django django-templates


    【解决方案1】:

    由于您只是获取文本,因此您最好的解决方案是编写一个模板过滤器,该过滤器将去除不在&lt;img&gt; html 标记中的内容。

    如果对象是 ImageField(或 FileField),则只能调用 url 属性,{{ movie.img.url }}

    更新

    好的,这是一个基本的,可能过于幼稚的模板过滤器供您使用。

    from django import template
    from django.template.defaultfilters import stringfilter
    import re
    
    register = template.Library()
    
    @register.filter(is_safe=True)
    @stringfilter
    def get_img_tag(value):
        result = re.search("<.*?>", value)
        if result:
            return result.group()
        return value
    

    用途:

    {{ movie.img|get_img_tag|safe }}
    

    【讨论】:

    • 但是如果 url 是单独的,这里我只是纯文本,其中包含 html。
    • movie 是一本字典,其中一个键是 u'img',它映射到 u'\n剧场版海报'我不确定它是否是 ImageField。我该怎么做?
    • Movie 是如何在你的 models.py 中定义的?
    • 没有models.py模型部分由我的队友处理,他正在使用mongodb数据库,调用他的api返回python字典列表,每个字典都相当于movie
    • 哦。游戏规则改变者。您可以编写一个模板过滤器来去除不在&lt;img&gt; 标签中的内容
    猜你喜欢
    • 2011-09-30
    • 1970-01-01
    • 1970-01-01
    • 2016-05-23
    • 2015-03-01
    • 2021-12-17
    • 1970-01-01
    • 2020-07-29
    • 1970-01-01
    相关资源
    最近更新 更多