I am formatting a string in python and I would lik开发者_Python百科e to use one of django's built in filters that is typically used in a template. Is there an easy way to use it in lines of code?
Generally, yes. For example, if your filter is in django.template.defaultfilters you can run:
from django.template.defaultfilters import slugify
slugify('what is that smell')
If you peruse the code though you might notice that many of these filters import code from django.utils.text and django.utils.html so you can also skip the middle-person indirection and import the function directly from those packages as they are now also publicly documented.
from django.utils.text import slugify
slugify('progress arcs in fits and starts')
Depends on the filter. In some cases you can import the module that contains the filter and access a helper function within the module, but in other cases you won't be so lucky. See the filter source for details.
Instead of using this in the template:
{{text | linebreaks}}
I used this to implement the linebreak filter:
from django.template.defaultfilters import linebreaks
text = "some text \n next line"
text = linebreaks(text)
gives:
<p>some text <br /> new line</p>
精彩评论