When should I use escape and safe in Django's template system?

前端 未结 4 1562
失恋的感觉
失恋的感觉 2020-12-01 13:31

If I have a box where people put comments, and then I display that comment like this...should I escape?

{{ c.title }}
相关标签:
4条回答
  • 2020-12-01 13:34

    Auto-escaping is on by default in django templates, so you don't need to use escape. Safe is used when you want to turn it off and let the template rendering system know that your date is safe in an un-escaped form. See the django docs for details:

    • Automatic HTML escaping
    0 讨论(0)
  • 2020-12-01 13:50

    Actually, it depends. Django's templating engine does escaping automatically, so you don't really need to escape.

    If you add template filter "safe" like {{c.title|safe}} then you do need to worry about things like html injection, because "safe" marks the string as such and it means that it won't be escaped.

    There is also an {% autoescape on %}...{% endautoescape %} template tag, where "on" can be changed to "off", if necessary. By default it's on and the tag is not needed.

    Other template engines may not be escaping by default, Jinja2 is one of them.

    0 讨论(0)
  • 2020-12-01 13:59

    HTML auto-escaping is on by default, so you don't need to manually escape in most cases, but not all!

    Dumping the contents of a variable inside an HTML element is fine:

    <p>{{ variable }}</p>
    

    Django will automatically escape the characters <, >, &, " and ', which is what is needed here.

    It's also OK to dump a variable inside an attribute, since " and ' are both escaped, but make sure you remember to include quotes, as spaces are not escaped:

    <span class="{{ variable }}">...</span> <!-- Good -->
    <span class={{ variable }}>...</span>   <!-- Bad -->
    

    If you want to use a string inside inline Javascript, you must use the escapejs filter, and don't forget the quotes. This protects against both escaping out of the quotes for the Javascript variable, and escaping out of the <script> tag using </script>:

    <script>
       var value = "{{ variable|escapejs }}";
    </script>
    
    0 讨论(0)
  • 2020-12-01 14:00

    Yes! What if they entered <script>alert('boom');</script> as the title?

    Django autoescape makes this much easier.

    0 讨论(0)
提交回复
热议问题