Sphinx documentation on Django templatetags templates

I am using Sphinx with autodoc to document my Django project.

The development guys want to have a documentation page about all the template tags that are defined in the project. Of course, I can make such a page by listing all the functions for processing templates manually, but I think this is NOT DRY, is it? In fact, template tag processing functions are marked by @register.inclusion_tagdecorator. Therefore, it seems possible and natural for some routine to collect all of them and add them to the documentation.

The same goes for filter functions.

I searched for it, searched for Django documentation, but in veins. I can hardly believe that such natural functionality was not implemented by someone.

Thanks for any tips.

+3
source share
3 answers

For recording, Django has an automatic documentation system (add django.contrib.admindocsto yours INSTALLED_APPS).

This will give you additional views in the administrator (usually in /admin/docs/) that represent your models, views (based on URLs), template tags and template filters.

Further documentation for this can be found in the admindocs section .

You can look at this code to include it in your documentation or in extensions for Django documentation.

+1
source

I did not stop at this stage and implemented the autodoc Sphinx extension.

2. autodoc Sphinx

"""
    Extension of Sphinx autodoc for Django template tag libraries.

    Usage:
       .. autotaglib:: some.module.templatetags.mod
           (options)

    Most of the `module` autodoc directive flags are supported by `autotaglib`.     

    Andrew "Hatter" Ponomarev, 2010
"""

from sphinx.ext.autodoc import ModuleDocumenter, members_option, members_set_option, bool_option, identity
from sphinx.util.inspect import safe_getattr

from django.template import get_library, InvalidTemplateLibrary

class TaglibDocumenter(ModuleDocumenter):           
    """
    Specialized Documenter subclass for Django taglibs.
    """
    objtype = 'taglib'
    directivetype = 'module'
    content_indent = u''

    option_spec = {
        'members': members_option, 'undoc-members': bool_option,
        'noindex': bool_option,
        'synopsis': identity,
        'platform': identity, 'deprecated': bool_option,
        'member-order': identity, 'exclude-members': members_set_option,
    }

    @classmethod
    def can_document_member(cls, member, membername, isattr, parent):
        # don't document submodules automatically
        return False

    def import_object(self):
        """
        Import the taglibrary.

        Returns True if successful, False if an error occurred.
        """
        # do an ordinary module import      
        if not super(ModuleDocumenter, self).import_object():
            return False        

        try:    
            # ask Django if specified module is a template tags library
            # and - if it is so - get and save Library instance         
            self.taglib = get_library(self.object.__name__)
            return True
        except InvalidTemplateLibrary, e:
            self.taglib = None
            self.directive.warn(unicode(e))

        return False    

    def get_object_members(self, want_all):
        """
        Decide what members of current object must be autodocumented.

        Return `(members_check_module, members)` where `members` is a
        list of `(membername, member)` pairs of the members of *self.object*.

        If *want_all* is True, return all members.  Else, only return those
        members given by *self.options.members* (which may also be none).
        """
        if want_all:
            return True, self.taglib.tags.items()
        else:
            memberlist = self.options.members or []
        ret = []
        for mname in memberlist:
            if mname in taglib.tags:
                ret.append((mname, self.taglib.tags[mname]))
            else:
                self.directive.warn(
                    'missing templatetag mentioned in :members: '
                    'module %s, templatetag %s' % (
                    safe_getattr(self.object, '__name__', '???'), mname))
        return False, ret

def setup(app):
    app.add_autodocumenter(TaglibDocumenter)

Sphinx autotaglib, , .

:

.. autotaglib:: lib.templatetags.bfmarkup
   :members:
   :undoc-members:
   :noindex:
+3

I solved the problem and would like to share my fragments - in case they are useful to someone.

Fragment 1. A simple documenter

import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings'

from django.template import get_library

def show_help(libname):
    lib = get_library(libname)
    print lib, ':'
    for tag in lib.tags:
        print tag
        print lib.tags[tag].__doc__


if __name__ == '__main__':
    show_help('lib.templatetags.bfmarkup')

Before you run this script, you must configure the PYTHONPATH environment variable.

0
source

Source: https://habr.com/ru/post/1768859/


All Articles