【问题标题】:django - custom filter not working properlydjango - 自定义过滤器无法正常工作
【发布时间】:2014-07-01 08:12:47
【问题描述】:

我正在编写一个自定义过滤器,如果给定文本中包含这个或多个字符,则该过滤器应使用<strong> 突出显示一个或多个字符。

这是我的自定义过滤器:

@register.filter(needs_autoescape=True)
def highlight(text, sterm, autoescape=None):
   if autoescape:
       esc = conditional_escape
   else:
       esc = lambda x: x
   result = text.replace(esc(sterm),'<strong>'+esc(sterm)+'</strong>')
   return mark_safe(result)

在模板中我{% load %}ed并以这种方式使用:

{{search_result_text|highlight:searchterm}}

问题是它突出显示匹配项之后的所有文本:

如您所见,第一个区块就是现在正在发生的事情。我想实现第二块。我搜索了level

我的代码有什么问题?

编辑:对不起,这是我的错字。我没有正确关闭&lt;strong&gt;,现在它就像一个魅力! :)。我把它留在这里,以便其他人可以使用它。

【问题讨论】:

  • 只需将您的解决方案作为答案发布并接受即可:)
  • @alecxe 你是对的。谢谢老兄:)
  • @alecxe 嘿 Alex,只是一个简单的问题:应用我的过滤器后,我想像这样 {{var|highlight:term|capfirst}} 制作 capfirstcapfirst 失败了,你知道为什么吗?
  • 当然,您可以尝试使用filter 链接过滤器,或者在highlight 之前应用capfirst :)
  • @alecxe 谢谢,但我首先应用了capfirst,然后是我的过滤器,没有成功。我想我需要过滤一下。

标签: python django django-custom-tags


【解决方案1】:

这是我的错字:我没有在过滤器函数中正确关闭&lt;strong&gt;

现在它就像一个魅力!

【讨论】:

    猜你喜欢
    • 2018-03-17
    • 2021-09-09
    • 2013-09-15
    • 1970-01-01
    • 2015-02-14
    • 2013-08-16
    • 2012-11-16
    相关资源
    最近更新 更多