Strip/Remove HTML tags (django utils)


/ Published in: Django
Save to your folder(s)



Copy this code and paste it in your HTML
  1. # To strip/remove HTML tags from an existing string we can use the strip_tags function.
  2.  
  3. # import the strip_tags
  4. from django.utils.html import strip_tags
  5.  
  6. # simple string with html inside.
  7. html = '<p>paragraph</p>'
  8. print html # will produce: <p>paragraph</p>
  9.  
  10. stripped = strip_tags(html)
  11. print stripped # will produce: paragraph
  12.  
  13. # This is also available as a template tag:
  14.  
  15. {{ somevalue|striptags }}
  16.  
  17.  
  18. # If you want to remove only specific tags you need to use the removetags
  19.  
  20.  
  21. from django.template.defaultfilters import removetags
  22. html = '<strong>Bold...</strong><p>paragraph....</p>'
  23. stripped = removetags(html, 'strong') # removes the strong only.
  24. stripped2 = removetags(html, 'strong p') # removes the strong AND p tags.
  25.  
  26. # Also available in template:
  27.  
  28. {{ value|removetags:"a span"|safe }}

URL: http://www.djangofoo.com/45/strip-remove-html-tags

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.