3

我正在使用带有 autodoc 的 Sphinx 来记录我的 Django 项目。

设计人员希望有关于项目中定义的所有模板标签的文档页面。当然,我可以通过手动枚举所有模板处理函数来制作这样的页面,但我认为它不是 DRY,不是吗?其实模板标签处理函数都是用@register.inclusion_tag装饰器标记的。因此,某些例程将它们全部收集并放入文档中似乎是可能且自然的。

过滤功能也是如此。

我已经用谷歌搜索了它,搜索了 Django 文档,但都在脉络中。我简直不敢相信这样一个自然的功能还没有被任何人实现过。

4

3 回答 3

3

我并没有在这一点上停下来,而是实现了一个 Sphinx 自动文档扩展。

片段 2.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:
于 2010-10-12T22:23:51.527 回答
1

作为记录,Django 有一个自动文档系统(添加django.contrib.admindocs到您的INSTALLED_APPS)。

这将在管理员(通常位于/admin/docs/)中为您提供额外的视图,这些视图代表您的模型、视图(基于 URL)、模板标签和模板过滤器。

更多文档可以在admindocs 部分找到。

You can take a look at that code to include it in your documentation or at the extensions for the Django documentation.

于 2011-06-08T18:23:53.927 回答
0

我解决了这个问题,并想分享我的片段——以防它们对某人有用。

片段 1. 简单的文档记录器

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')

在运行此脚本之前,您应该设置 PYTHONPATH 环境变量。

于 2010-10-12T22:14:38.847 回答