Ticket #2016: 0003-Adds-documentation-for-object_tag.diff

File 0003-Adds-documentation-for-object_tag.diff, 2.1 KB (added by marcusf, 6 years ago)
  • docs/howto/custom-template-tags.txt

    diff --git a/docs/howto/custom-template-tags.txt b/docs/howto/custom-template-tags.txt
    index c6f7677..6b78711 100644
    a b class, like so:: 
    783783The difference here is that ``do_current_time()`` grabs the format string and
    784784the variable name, passing both to ``CurrentTimeNode3``.
    785785
     786Shortcut for loading objects into template variables
     787~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     788
     789.. versionadded: 1.2
     790
     791If you only need to retrieve and store an object in a template variable, it
     792might seem cumbersome to write both a renderer and a compilation function
     793for such an easy task.
     794
     795That is why Django provides yet another shortcut -- ``object_tag`` -- which
     796makes it easy to write tags that loads objects into template variables.
     797
     798Its use is very similar to ``simple_tag`` in the way that it takes care of
     799all the argument parsing for you, and only requires a single return value --
     800the object you'd like to insert into the template variable.
     801
     802Example::
     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
     809Or 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
     815This tag returns the latest ``Poll``-objects, sorted by descending order, and
     816limited by the value of ``max_num``. Its use in a template would look like
     817this:
     818
     819.. code-block:: html+django
     820
     821    {% get_latest_polls 5 as latest_polls %}
     822
     823Which would retrieve the 5 latest polls and store them inside a template
     824variable named "latest_polls".
     825
     826Note 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
     832Where ``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
     834should be stored.
     835
    786836Parsing until another block tag
    787837~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    788838
Back to Top