Changeset 6798
- Timestamp:
- 12/01/07 12:38:12 (11 months ago)
- Files:
-
- django/trunk/docs/templates_python.txt (modified) (6 diffs)
- django/trunk/docs/templates.txt (modified) (4 diffs)
Legend:
- Unmodified
- Added
- Removed
- Modified
- Copied
- Moved
django/trunk/docs/templates_python.txt
r6743 r6798 728 728 **New in Django development version** 729 729 730 When you are writing a custom filter, you need to give some thought to how 731 this filter will interact with Django's auto-escaping behaviour. Firstly, you 732 should realise that there are three types of strings that can be passed around 733 inside the template code: 734 735 * raw strings are the native Python ``str`` or ``unicode`` types. On 736 output, they are escaped if auto-escaping is in effect and presented 737 unchanged, otherwise. 738 739 * "safe" strings are strings that are safe from further escaping at output 740 time. Any necessary escaping has already been done. They are commonly used 741 for output that contains raw HTML that is intended to be intrepreted on the 742 client side. 743 744 Internally, these strings are of type ``SafeString`` or ``SafeUnicode``, 745 although they share a common base class in ``SafeData``, so you can test 746 for them using code like:: 747 748 if isinstance(value, SafeData): 749 # Do something with the "safe" string. 750 751 * strings which are marked as "needing escaping" are *always* escaped on 752 output, regardless of whether they are in an ``autoescape`` block or not. 753 These strings are only escaped once, however, even if auto-escaping 754 applies. This type of string is internally represented by the types 755 ``EscapeString`` and ``EscapeUnicode``. You will not normally need to worry 756 about these; they exist for the implementation of the ``escape`` filter. 757 758 When you are writing a filter, your code will typically fall into one of two 759 situations: 760 761 1. Your filter does not introduce any HTML-unsafe characters (``<``, ``>``, 762 ``'``, ``"`` or ``&``) into the result that were not already present. In 763 this case, you can let Django take care of all the auto-escaping handling 764 for you. All you need to do is put the ``is_safe`` attribute on your 765 filter function and set it to ``True``. This attribute tells Django that 766 is a "safe" string is passed into your filter, the result will still be 767 "safe" and if a non-safe string is passed in, Django will automatically 768 escape it, if necessary. The reason ``is_safe`` is necessary is because 769 there are plenty of normal string operations that will turn a ``SafeData`` 770 object back into a normal ``str`` or ``unicode`` object and, rather than 771 try to catch them all, which would be very difficult, Django repairs the 772 damage after the filter has completed. 773 774 For example, suppose you have a filter that adds the string ``xx`` to the 775 end of any input. Since this introduces no dangerous HTML characters into 776 the result (aside from any that were already present), you should mark 777 your filter with ``is_safe``:: 730 When writing a custom filter, give some thought to how the filter will interact 731 with Django's auto-escaping behavior. Note that three types of strings can be 732 passed around inside the template code: 733 734 * **Raw strings** are the native Python ``str`` or ``unicode`` types. On 735 output, they're escaped if auto-escaping is in effect and presented 736 unchanged, otherwise. 737 738 * **Safe strings** are strings that have been marked safe from further 739 escaping at output time. Any necessary escaping has already been done. 740 They're commonly used for output that contains raw HTML that is intended 741 to be interpreted as-is on the client side. 742 743 Internally, these strings are of type ``SafeString`` or ``SafeUnicode``. 744 They share a common base class of ``SafeData``, so you can test 745 for them using code like:: 746 747 if isinstance(value, SafeData): 748 # Do something with the "safe" string. 749 750 * **Strings marked as "needing escaping"** are *always* escaped on 751 output, regardless of whether they are in an ``autoescape`` block or not. 752 These strings are only escaped once, however, even if auto-escaping 753 applies. 754 755 Internally, these strings are of type ``EscapeString`` or 756 ``EscapeUnicode``. Generally you don't have to worry about these; they 757 exist for the implementation of the ``escape`` filter. 758 759 Template filter code falls into one of two situations: 760 761 1. Your filter does not introduce any HTML-unsafe characters (``<``, ``>``, 762 ``'``, ``"`` or ``&``) into the result that were not already present. In 763 this case, you can let Django take care of all the auto-escaping 764 handling for you. All you need to do is put the ``is_safe`` attribute on 765 your filter function and set it to ``True``, like so:: 766 767 @register.filter 768 def myfilter(value): 769 return value 770 myfilter.is_safe = True 771 772 This attribute tells Django that if a "safe" string is passed into your 773 filter, the result will still be "safe" and if a non-safe string is 774 passed in, Django will automatically escape it, if necessary. 775 776 You can think of this as meaning "this filter is safe -- it doesn't 777 introduce any possibility of unsafe HTML." 778 779 The reason ``is_safe`` is necessary is because there are plenty of 780 normal string operations that will turn a ``SafeData`` object back into 781 a normal ``str`` or ``unicode`` object and, rather than try to catch 782 them all, which would be very difficult, Django repairs the damage after 783 the filter has completed. 784 785 For example, suppose you have a filter that adds the string ``xx`` to the 786 end of any input. Since this introduces no dangerous HTML characters to 787 the result (aside from any that were already present), you should mark 788 your filter with ``is_safe``:: 778 789 779 790 @register.filter … … 782 793 add_xx.is_safe = True 783 794 784 When this filter is used in a template where auto-escaping is enabled, 785 Django will escape the output whenever the input is not already marked as 786 "safe". 787 788 By default, ``is_safe`` defaults to ``False`` and you can omit it from 789 any filters where it isn't required. 790 791 Be careful when deciding if your filter really does leave safe strings 792 as safe. Sometimes if you are *removing* characters, you can 793 inadvertently leave unbalanced HTML tags or entities in the result. 794 For example, removing a ``>`` from the input might turn ``<a>`` into 795 ``<a``, which would need to be escaped on output to avoid causing 796 problems. Similarly, removing a semicolon (``;``) can turn ``&`` 797 into ``&``, which is no longer a valid entity and thus needs 798 further escaping. Most cases won't be nearly this tricky, but keep an 799 eye out for any problems like that when reviewing your code. 800 801 2. Alternatively, your filter code can manually take care of any necessary 802 escaping. This is usually necessary when you are introducing new HTML 803 markup into the result. You want to mark the output as safe from further 804 escaping so that your HTML markup isn't escaped further, so you'll need to 805 handle the input yourself. 806 807 To mark the output as a safe string, use 808 ``django.utils.safestring.mark_safe()``. 809 810 Be careful, though. You need to do more than just mark the output as 811 safe. You need to ensure it really *is* safe and what you do will often 812 depend upon whether or not auto-escaping is in effect. The idea is to 813 write filters than can operate in templates where auto-escaping is either 814 on or off in order to make things easier for your template authors. 815 816 In order for you filter to know the current auto-escaping state, set the 817 ``needs_autoescape`` attribute to ``True`` on your function (if you don't 818 specify this attribute, it defaults to ``False``). This attribute tells 819 Django that your filter function wants to be passed an extra keyword 820 argument, called ``autoescape`` that is ``True`` is auto-escaping is in 821 effect and ``False`` otherwise. 822 823 An example might make this clearer. Let's write a filter that emphasizes 824 the first character of a string:: 825 826 from django.utils.html import conditional_escape 827 from django.utils.safestring import mark_safe 828 829 def initial_letter_filter(text, autoescape=None): 830 first, other = text[0] ,text[1:] 831 if autoescape: 832 esc = conditional_escape 833 else: 834 esc = lambda x: x 835 result = '<strong>%s</strong>%s' % (esc(first), esc(other)) 836 return mark_safe(result) 837 initial_letter_filter.needs_autoescape = True 838 839 The ``needs_autoescape`` attribute on the filter function and the 840 ``autoescape`` keyword argument mean that our function will know whether 841 or not automatic escaping is in effect when the filter is called. We use 842 ``autoescape`` to decide whether the input data needs to be passed through 843 ``django.utils.html.conditional_escape`` or not (in the latter case, we 844 just use the identity function as the "escape" function). The 845 ``conditional_escape()`` function is like ``escape()`` except it only 846 escapes input that is **not** a ``SafeData`` instance. If a ``SafeData`` 847 instance is passed to ``conditional_escape()``, the data is returned 848 unchanged. 849 850 Finally, in the above example, we remember to mark the result as safe 851 so that our HTML is inserted directly into the template without further 852 escaping. 853 854 There is no need to worry about the ``is_safe`` attribute in this case 855 (although including it wouldn't hurt anything). Whenever you are manually 856 handling the auto-escaping issues and returning a safe string, the 857 ``is_safe`` attribute won't change anything either way. 795 When this filter is used in a template where auto-escaping is enabled, 796 Django will escape the output whenever the input is not already marked as 797 "safe". 798 799 By default, ``is_safe`` defaults to ``False``, and you can omit it from 800 any filters where it isn't required. 801 802 Be careful when deciding if your filter really does leave safe strings 803 as safe. If you're *removing* characters, you might inadvertently leave 804 unbalanced HTML tags or entities in the result. For example, removing a 805 ``>`` from the input might turn ``<a>`` into ``<a``, which would need to 806 be escaped on output to avoid causing problems. Similarly, removing a 807 semicolon (``;``) can turn ``&`` into ``&``, which is no longer a 808 valid entity and thus needs further escaping. Most cases won't be nearly 809 this tricky, but keep an eye out for any problems like that when 810 reviewing your code. 811 812 2. Alternatively, your filter code can manually take care of any necessary 813 escaping. This is necessary when you're introducing new HTML markup into 814 the result. You want to mark the output as safe from further 815 escaping so that your HTML markup isn't escaped further, so you'll need 816 to handle the input yourself. 817 818 To mark the output as a safe string, use ``django.utils.safestring.mark_safe()``. 819 820 Be careful, though. You need to do more than just mark the output as 821 safe. You need to ensure it really *is* safe, and what you do depends on 822 whether auto-escaping is in effect. The idea is to write filters than 823 can operate in templates where auto-escaping is either on or off in 824 order to make things easier for your template authors. 825 826 In order for you filter to know the current auto-escaping state, set the 827 ``needs_autoescape`` attribute to ``True`` on your function. (If you 828 don't specify this attribute, it defaults to ``False``). This attribute 829 tells Django that your filter function wants to be passed an extra 830 keyword argument, called ``autoescape``, that is ``True`` is 831 auto-escaping is in effect and ``False`` otherwise. 832 833 For example, let's write a filter that emphasizes the first character of 834 a string:: 835 836 from django.utils.html import conditional_escape 837 from django.utils.safestring import mark_safe 838 839 def initial_letter_filter(text, autoescape=None): 840 first, other = text[0], text[1:] 841 if autoescape: 842 esc = conditional_escape 843 else: 844 esc = lambda x: x 845 result = '<strong>%s</strong>%s' % (esc(first), esc(other)) 846 return mark_safe(result) 847 initial_letter_filter.needs_autoescape = True 848 849 The ``needs_autoescape`` attribute on the filter function and the 850 ``autoescape`` keyword argument mean that our function will know whether 851 automatic escaping is in effect when the filter is called. We use 852 ``autoescape`` to decide whether the input data needs to be passed through 853 ``django.utils.html.conditional_escape`` or not. (In the latter case, we 854 just use the identity function as the "escape" function.) The 855 ``conditional_escape()`` function is like ``escape()`` except it only 856 escapes input that is **not** a ``SafeData`` instance. If a ``SafeData`` 857 instance is passed to ``conditional_escape()``, the data is returned 858 unchanged. 859 860 Finally, in the above example, we remember to mark the result as safe 861 so that our HTML is inserted directly into the template without further 862 escaping. 863 864 There's no need to worry about the ``is_safe`` attribute in this case 865 (although including it wouldn't hurt anything). Whenever you manually 866 handle the auto-escaping issues and return a safe string, the 867 ``is_safe`` attribute won't change anything either way. 858 868 859 869 Writing custom template tags … … 982 992 The output from template tags is **not** automatically run through the 983 993 auto-escaping filters. However, there are still a couple of things you should 984 keep in mind when writing a template tag :994 keep in mind when writing a template tag. 985 995 986 996 If the ``render()`` function of your template stores the result in a context … … 992 1002 993 1003 Also, if your template tag creates a new context for performing some 994 sub-rendering, you should be careful to set the auto-escape attribute to the 995 current context's value. The ``__init__`` method for the ``Context`` class 996 takes a parameter called ``autoescape`` that you can use for this purpose. For 997 example:: 1004 sub-rendering, set the auto-escape attribute to the current context's value. 1005 The ``__init__`` method for the ``Context`` class takes a parameter called 1006 ``autoescape`` that you can use for this purpose. For example:: 998 1007 999 1008 def render(self, context): … … 1002 1011 # ... Do something with new_context ... 1003 1012 1004 This is not a very common situation, but it is sometimes useful, particularly1005 if you are rendering atemplate yourself. For example::1013 This is not a very common situation, but it's useful if you're rendering a 1014 template yourself. For example:: 1006 1015 1007 1016 def render(self, context): … … 1011 1020 If we had neglected to pass in the current ``context.autoescape`` value to our 1012 1021 new ``Context`` in this example, the results would have *always* been 1013 automatically escaped, which may not be the desired behavio ur if the template1022 automatically escaped, which may not be the desired behavior if the template 1014 1023 tag is used inside a ``{% autoescape off %}`` block. 1015 1024 django/trunk/docs/templates.txt
r6792 r6798 311 311 **New in Django development version** 312 312 313 A very real problem when creating HTML (and other) output using templates and 314 variable substitution is the possibility of accidently inserting some variable 315 value that affects the resulting HTML. For example, a template fragment such as 316 :: 313 When generating HTML from templates, there's always a risk that a variable will 314 include characters that affect the resulting HTML. For example, consider this 315 template fragment:: 317 316 318 317 Hello, {{ name }}. 319 318 320 seems like a harmless way to display the user's name. However, if you are 321 displaying data that the user entered directly and they had entered their name as::319 At first, this seems like a harmless way to display a user's name, but consider 320 what would happen if the user entered his name as this:: 322 321 323 322 <script>alert('hello')</script> 324 323 325 this would always display a Javascript alert box when the page was loaded. 326 Similarly, if you were displaying some data generated by another process and it 327 contained a '<' symbol, you couldn't just dump this straight into your HTML, 328 because it would be treated as the start of an element. The effects of these 329 sorts of problems can vary from merely annoying to allowing exploits via `Cross 330 Site Scripting`_ (XSS) attacks. 331 332 .. _Cross Site Scripting: http://en.wikipedia.org/wiki/Cross-site_scripting 333 334 In order to provide some protection against these problems, Django 335 provides automatic (but controllable) HTML escaping for data coming from 336 tempate variables. Inside this tag, any data that comes from template 337 variables is examined to see if it contains one of the five HTML characters 338 (<, >, ', " and &) that often need escaping and those characters are converted 339 to their respective HTML entities. It causes no harm if a character is 340 converted to an entity when it doesn't need to be, so all five characters are 341 always converted. 342 343 Since some variables will contain data that is *intended* to be rendered 344 as HTML, template tag and filter writers can mark their output strings as 345 requiring no further escaping. For example, the ``unordered_list`` filter is 346 designed to return raw HTML and we want the template processor to simply 347 display the results as returned, without applying any escaping. That is taken 348 care of by the filter. The template author need do nothing special in that 349 case. 350 351 By default, automatic HTML escaping is always applied. However, sometimes you 352 will not want this to occur (for example, if you're using the templating 353 system to create an email). To control automatic escaping inside your template, 354 wrap the affected content in the ``autoescape`` tag, like so:: 324 With this name value, the template would be rendered as:: 325 326 Hello, <script>alert('hello')</script> 327 328 ...which means the browser would pop-up a JavaScript alert box! 329 330 Similarly, what if the name contained a ``'<'`` symbol, like this? 331 332 <b>username 333 334 That would result in a rendered template like this:: 335 336 Hello, <b>username 337 338 ...which, in turn, would result in the remainder of the Web page being bolded! 339 340 Clearly, user-submitted data shouldn't be trusted blindly and inserted directly 341 into your Web pages, because a malicious user could use this kind of hole to 342 do potentially bad things. This type of security exploit is called a 343 Cross Site Scripting`_ (XSS) attack. 344 345 To avoid this problem, you have two options: 346 347 * One, you can make sure to run each untrusted variable through the 348 ``escape`` filter (documented below), which converts potentially harmful 349 HTML characters to unharmful ones. This was default the default solution 350 in Django for its first few years, but the problem is that it puts the 351 onus on *you*, the developer / template author, to ensure you're escaping 352 everything. It's easy to forget to escape data. 353 354 * Two, you can take advantage of Django's automatic HTML escaping. The 355 remainder of this section describes how auto-escaping works. 356 357 By default in the Django development version, every template automatically 358 escapes the output of every variable tag. Specifically, these five characters 359 are escaped: 360 361 * ``<`` is converted to ``<`` 362 * ``>`` is converted to ``>`` 363 * ``'`` (single quote) is converted to ``'`` 364 * ``"`` (double quote) is converted to ``"`` 365 * ``&`` is converted to ``&`` 366 367 Again, we stress that this behavior is on by default. If you're using Django's 368 template system, you're protected. 369 370 How to turn it off 371 ------------------ 372 373 If you don't want data to be auto-escaped, on a per-site, per-template level or 374 per-variable level, you can turn it off in several ways. 375 376 Why would you want to turn it off? Because sometimes, template variables 377 contain data that you *intend* to be rendered as raw HTML, in which case you 378 don't want their contents to be escaped. For example, you might store a blob of 379 HTML in your database and want to embed that directly into your template. Or, 380 you might be using Django's template system to produce text that is *not* HTML 381 -- like an e-mail message, for instance. 382 383 For individual variables 384 ~~~~~~~~~~~~~~~~~~~~~~~~ 385 386 To disable auto-escaping for an individual variable, use the ``safe`` filter:: 387 388 This will be escaped: {{ data }} 389 This will not be escaped: {{ data|safe }} 390 391 Think of *safe* as shorthand for *safe from further escaping* or *can be 392 safely interpreted as HTML*. In this example, if ``data`` contains ``'<b>'``, 393 the output will be:: 394 395 This will be escaped: <b> 396 This will not be escaped: <b> 397 398 For template blocks 399 ~~~~~~~~~~~~~~~~~~~ 400 401 To control auto-escaping for a template, wrap the template (or just a 402 particular section of the template) in the ``autoescape`` tag, like so:: 355 403 356 404 {% autoescape off %} … … 358 406 {% endautoescape %} 359 407 408 The ``autoescape`` tag takes either ``on`` or ``off`` as its argument. At 409 times, you might want to force auto-escaping when it would otherwise be 410 disabled. Here is an example template:: 411 412 Auto-escaping is on by default. Hello {{ name }} 413 414 {% autoescape off %} 415 This will not be auto-escaped: {{ data }}. 416 417 Nor this: {{ other_data }} 418 {% autoescape on %} 419 Auto-escaping applies again: {{ name }} 420 {% endautoescape %} 421 {% endautoescape %} 422 360 423 The auto-escaping tag passes its effect onto templates that extend the 361 424 current one as well as templates included via the ``include`` tag, just like 362 all block tags. 363 364 The ``autoescape`` tag takes either ``on`` or ``off`` as its argument. At times, you might want to force auto-escaping when it would otherwise be disabled. For example:: 365 366 Auto-escaping is on by default. Hello {{ name }} 425 all block tags. For example:: 426 427 # base.html 367 428 368 429 {% autoescape off %} 369 This will not be auto-escaped: {{ data }}. 370 371 Nor this: {{ other_data }} 372 {% autoescape on %} 373 Auto-escaping applies again, {{ name }} 374 {% endautoescape %} 430 <h1>{% block title %}</h1> 431 {% block content %} 375 432 {% endautoescape %} 376 433 377 For individual variables, the ``safe`` filter can also be used to indicate 378 that the contents should not be automatically escaped:: 379 380 This will be escaped: {{ data }} 381 This will not be escaped: {{ data|safe }} 382 383 Think of *safe* as shorthand for *safe from further escaping* or *can be 384 safely interpreted as HTML*. In this example, if ``data`` contains ``'<a>'``, 385 the output will be:: 386 387 This will be escaped: <a> 388 This will not be escaped: <a> 389 390 Generally, you won't need to worry about auto-escaping very much. View 391 developers and custom filter authors need to think about when their data 392 shouldn't be escaped and mark it appropriately. They are in a better position 393 to know when that should happen than the template author, so it is their 394 responsibility. By default, all output is escaped unless the template 395 processor is explicitly told otherwise. 396 397 You should also note that if you are trying to write a template that might be 398 used in situations where automatic escaping is enabled or disabled and you 399 don't know which (such as when your template is included in other templates), 400 you can safely write as if you were in an ``{% autoescape off %}`` situation. 401 Scatter ``escape`` filters around for any variables that need escaping. When 402 auto-escaping is on, these extra filters won't change the output -- any 403 variables that use the ``escape`` filter do not have further automatic 404 escaping applied to them. 434 435 # child.html 436 437 {% extends "base.html" %} 438 {% block title %}This & that{% endblock %} 439 {% block content %}<b>Hello!</b>{% endblock %} 440 441 Because auto-escaping is turned off in the base template, it will also be 442 turned off in the child template, resulting in the following rendered HTML:: 443 444 <h1>This & that</h1> 445 <b>Hello!</b> 446 447 Notes 448 ----- 449 450 Generally, template authors don't need to worry about auto-escaping very much. 451 Developers on the Python side (people writing views and custom filters) need to 452 think about the cases in which data shouldn't be escaped, and mark data 453 appropriately, so things Just Work in the template. 454 455 If you're creating a template that might be used in situations where you're 456 not sure whether auto-escaping is enabled, then add an ``escape`` filter to any 457 variable that needs escaping. When auto-escaping is on, there's no danger of 458 the ``escape`` filter *double-escaping* data -- the ``escape`` filter does not 459 affect auto-escaped variables. 405 460 406 461 String literals and automatic escaping 407 462 -------------------------------------- 408 463 409 Sometimes you will pass a string literal as an argument to a filter. For 410 example:: 464 As we mentioned earlier, filter arguments can be strings:: 411 465 412 466 {{ data|default:"This is a string literal." }} 413 467 414 468 All string literals are inserted **without** any automatic escaping into the 415 template , if they are used (it's as if they were all passed through the416 ``safe`` filter). The reasoning behind this is that the template author is in 417 control of what goes into the string literal, so they can make sure the text 418 is correctlyescaped when the template is written.469 template -- they act as if they were all passed through the ``safe`` filter. 470 The reasoning behind this is that the template author is in control of what 471 goes into the string literal, so they can make sure the text is correctly 472 escaped when the template is written. 419 473 420 474 This means you would write :: … … 427 481 428 482 This doesn't affect what happens to data coming from the variable itself. 429 The variable's contents are still automatically escaped, if necessary, since483 The variable's contents are still automatically escaped, if necessary, because 430 484 they're beyond the control of the template author. 431 485 … … 1231 1285 Escapes a string's HTML. Specifically, it makes these replacements: 1232 1286 1233 * `` "&"`` to ``"&"``1234 * `` <`` to ``"<"``1235 * `` >`` to ``">"``1236 * `` '"'`` (double quote) to ``'"'``1237 * `` "'"`` (single quote) to ``'''``1287 * ``<`` is converted to ``<`` 1288 * ``>`` is converted to ``>`` 1289 * ``'`` (single quote) is converted to ``'`` 1290 * ``"`` (double quote) is converted to ``"`` 1291 * ``&`` is converted to ``&`` 1238 1292 1239 1293 The escaping is only applied when the string is output, so it does not matter
