Django templates stripping spaces?

后端 未结 8 450
心在旅途
心在旅途 2021-01-08 00:06

I\'m having trouble with Django templates and CharField models.

So I have a model with a CharField that creates a slug that replaces spaces with underscores. If I cr

8条回答
  •  终归单人心
    2021-01-08 00:32

    This tag keeps spaces and newlines. I copied Django's own tag linebreaksbr and then added a line to replace the spaces with nbsp. It does not replace single spaces so text source is still readable. I wrote this because I couldn't get the spacify tag (other answer) to work with linebreaksbr.

    from django.template.defaultfilters import stringfilter
    from django.utils.safestring import mark_safe, SafeData
    from django.utils.text import normalize_newlines
    from django.utils.html import escape
    
    @register.filter(is_safe=True, needs_autoescape=True)
    @stringfilter
    def keep_spacing(value, autoescape=None):
        autoescape = autoescape and not isinstance(value, SafeData)
        value = normalize_newlines(value)
        if autoescape:
            value = escape(value)
        value = mark_safe(value.replace('  ', '  '))             
        return mark_safe(value.replace('\n', '
    '))

提交回复
热议问题