| 786 | Shortcut for loading objects into template variables |
| 787 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 788 | |
| 789 | .. versionadded: 1.2 |
| 790 | |
| 791 | If you only need to retrieve and store an object in a template variable, it |
| 792 | might seem cumbersome to write both a renderer and a compilation function |
| 793 | for such an easy task. |
| 794 | |
| 795 | That is why Django provides yet another shortcut -- ``object_tag`` -- which |
| 796 | makes it easy to write tags that loads objects into template variables. |
| 797 | |
| 798 | Its use is very similar to ``simple_tag`` in the way that it takes care of |
| 799 | all the argument parsing for you, and only requires a single return value -- |
| 800 | the object you'd like to insert into the template variable. |
| 801 | |
| 802 | Example:: |
| 803 | |
| 804 | def get_latest_polls(max_num): |
| 805 | return Poll.objects.order_by('-pub_date')[:max_num] |
| 806 | |
| 807 | register.object_tag(get_latest_polls) |
| 808 | |
| 809 | Or if you wish to use the Python 2.4 decorator syntax:: |
| 810 | |
| 811 | @register.object_tag |
| 812 | def get_latest_polls(max_num): |
| 813 | return Poll.objects.order_by('-pub_date')[:max_num] |
| 814 | |
| 815 | This tag returns the latest ``Poll``-objects, sorted by descending order, and |
| 816 | limited by the value of ``max_num``. Its use in a template would look like |
| 817 | this: |
| 818 | |
| 819 | .. code-block:: html+django |
| 820 | |
| 821 | {% get_latest_polls 5 as latest_polls %} |
| 822 | |
| 823 | Which would retrieve the 5 latest polls and store them inside a template |
| 824 | variable named "latest_polls". |
| 825 | |
| 826 | Note that the following syntax is *mandatory* for all object_tag's: |
| 827 | |
| 828 | .. code-block:: html+django |
| 829 | |
| 830 | {% tag_name [args] as <var_name> %} |
| 831 | |
| 832 | Where ``args`` is the arguments for the templatetag ``tag_name``, and |
| 833 | ``var_name`` is the name of the template variable in which the returned object |
| 834 | should be stored. |
| 835 | |