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

问题描述



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



但是,如果我创建了一个对象,则会创建Somename Somesurname (注意第二个空格),slug 创建Somename__Somesurname 虽然在Django控制台上,我将它看作为< Object:Somename Somesurname> ,在模板上显示为 Somename Somesurname



Django模板是否以某种方式剥离空格?有没有一个过滤器可以使用它的空格来获取名称?

解决方案

让我先说说@ DNS的答案是正确的是为什么空格不显示。



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



用法:

  {hey there world| spacify}} 

输出将为 hey&那里有& nbsp;& nbsp; world



这是代码:



来自django.template的库
从django.template.defaultfilters导入stringfilter
从django.utils.html导入条件_escape
从django.utils .safestring import mark_safe
import re

register = Library()

@stringfilter
def spacify(value,autoescape = None):
如果autoescape:
esc = conditional_escape
else:
esc = lambda x :x
return mark_safe(re.sub('\s','&'+'nbsp;',esc(value)))
spacify.needs_autoescape = True
注册。过滤器(空格)

有关模板过滤器的工作原理以及如何安装它们的注意事项,。


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 create an object, Somename Somesurname, this creates slug Somename_Somesurname and gets displayed as expected on the template.

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.

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

解决方案

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.

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

08-30 07:02