本文介绍了Django 模板剥离空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 Django 模板和 CharField 模型时遇到问题.

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

所以我有一个带有 CharField 的模型,它创建了一个用下划线替换空格的 slug.如果我创建一个对象 Somename Somesurname,这会创建 slug Somename_Somesurname 并在模板上按预期显示.

So I have a model with a CharField that creates a slug that replaces spaces with underscores. If I create an object, Somename Somesurname, this creates slug Somename_Somesurname and gets displayed as expected on the template.

但是,如果我创建一个对象,Somename Somesurname(注意第二个空格),将创建 slug Somename__Somesurname,尽管在​​ Django 控制台上我将其视为 ,在模板上显示为Somename Somesurname.

However, if I create an object, Somename Somesurname (notice the second space), slug Somename__Somesurname is created, and although on the Django console I see this as <Object: Somename Somesurname>, on the template it is displayed as Somename Somesurname.

那么 Django 模板会以某种方式去除空格吗?是否有过滤器可以用来获取带有空格的名称?

So do Django templates somehow strip spaces? Is there a filter I can use to get the name with its spaces?

推荐答案

让我先说@DNS 的答案是正确的,为什么没有显示空格.

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

考虑到这一点,此模板过滤器将用 &nbsp;

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

用法:

{{ "hey there  world"|spacify }}

输出将是 hey&nbsp;there&nbsp;&nbsp;world

代码如下:

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.

这篇关于Django 模板剥离空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-05 00:15