Django templates stripping spaces?

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

    Slugify removes all leading spaces, you'll need to rewrite this as a custom template tag to get the behaviour you're after. The original filter code looks like this

    def slugify(value):
       """
       Normalizes string, converts to lowercase, removes non-alpha characters,
       and converts spaces to hyphens.
       """
       import unicodedata
       value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore')
       value = unicode(re.sub('[^\w\s-]', '', value).strip().lower())
       return mark_safe(re.sub('[-\s]+', '-', value))
    

    which changes "some   string" into "some-string" killing the extra whitespace. You could change it like so:

    def new_slugify(value):
       """
       Normalizes string, converts to lowercase, removes non-alpha characters,
       and converts spaces to hyphens, does not remove leading whitespace.
       """
       import unicodedata
       value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore')
       value = unicode(re.sub('[^\w\s-]', '', value).strip().lower())
       return mark_safe(re.sub('[-\s]', '-', value))
    

    Which will result in the following behaviour: "Some  String here" to "some--string-here"

    You still might have problems as mentioned before with how html treats extra whitespace, you'd have to write another, deslugify filter.

提交回复
热议问题