Opened 5 years ago

Closed 5 years ago

#13379 closed (wontfix)

New template filter suggestion (wrap)

Reported by: david.arakelian@… Owned by: nobody
Component: Template system Version: master
Severity: Keywords: wrap, template filter
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: UI/UX:

Description

We came across a use case today for wrapping variables in styles If they are not None/Empty/False...

E.g. If a variable exists add a break tag after it or if a value exists then wrap it in a <p></p> tag.
So we wrote a simple template tag that might be of interest to the community.

Template tag:

from django import template
from django.template.defaultfilters import stringfilter
from django.utils.safestring import mark_safe

register = template.Library()

@register.filter
@stringfilter
def wrap(value, arg):
    if value and value != '':
        return mark_safe(arg % value) # decision needed with |safe
    return value

Usage:

{{ var|wrap:"%s<br />" }} or
{{ var|wrap:"<p>%s</p>" }}

Change History (1)

comment:1 Changed 5 years ago by russellm

  • milestone 1.2 deleted
  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Resolution set to wontfix
  • Status changed from new to closed

I'm afraid I don't see the benefit here. What you describe is already possible with:

{% if var %}<p>{{ var }}</p>{% endif %}

I'm not convinced that a template filter is an inhernetly cleaner way of representing this.

Note: See TracTickets for help on using tickets.
Back to Top