Django templates stripping spaces?

后端 未结 8 447
心在旅途
心在旅途 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:53

    There is a built-in template tag spaceless

    {% spaceless %}
        <p>
            <a href="foo/">Foo</a>
        </p>
    {% endspaceless %}
    

    Which results:

    <p><a href="foo/">Foo</a></p>
    

    Read more in django documentation.

    0 讨论(0)
  • 2021-01-08 00:54

    Let me preface this by saying @DNS's answer is correct as to why the spaces are not showing.

    With that in mind, this template filter will replace any spaces in the string with &nbsp;

    Usage:

    {{ "hey there  world"|spacify }}
    

    Output would be hey&nbsp;there&nbsp;&nbsp;world

    Here is the code:

    from django.template import Library
    from django.template.defaultfilters import stringfilter
    from django.utils.html import conditional_escape
    from django.utils.safestring import mark_safe
    import re
    
    register = Library()
    
    @stringfilter
    def spacify(value, autoescape=None):
        if autoescape:
        esc = conditional_escape
        else:
        esc = lambda x: x
        return mark_safe(re.sub('\s', '&'+'nbsp;', esc(value)))
    spacify.needs_autoescape = True
    register.filter(spacify)
    

    For notes on how template filters work and how to install them, check out the docs.

    0 讨论(0)
提交回复
热议问题