PageRenderTime 21ms CodeModel.GetById 12ms app.highlight 5ms RepoModel.GetById 1ms app.codeStats 0ms

/hyde/ext/plugins/auto_extend.py

http://github.com/hyde/hyde
Python | 55 lines | 34 code | 9 blank | 12 comment | 6 complexity | 0007bc234a02f601141ded750e0a9753 MD5 | raw file
 1# -*- coding: utf-8 -*-
 2"""
 3Autoextend plugin
 4"""
 5
 6from hyde.plugin import Plugin
 7import re
 8
 9class AutoExtendPlugin(Plugin):
10    """
11    The plugin class for extending templates using metadata.
12    """
13
14    def __init__(self, site):
15        super(AutoExtendPlugin, self).__init__(site)
16
17    def begin_text_resource(self, resource, text):
18        """
19        If the meta data for the resource contains a layout attribute,
20        and there is no extends statement, this plugin automatically adds
21        an extends statement to the top of the file.
22        """
23
24        if not resource.uses_template:
25            return text
26
27        layout = None
28        block = None
29        try:
30            layout = resource.meta.extends
31        except AttributeError:
32            pass
33
34        try:
35            block = resource.meta.default_block
36        except AttributeError:
37            pass
38
39        if layout:
40            self.logger.debug("Autoextending %s with %s" % (
41                resource.relative_path, layout))
42            extends_pattern = self.template.patterns['extends']
43
44            if not re.search(extends_pattern, text):
45                extended_text = self.template.get_extends_statement(layout)
46                extended_text += '\n'
47                if block:
48                    extended_text += ('%s\n%s\n%s' %
49                                        (self.t_block_open_tag(block),
50                                            text,
51                                            self.t_block_close_tag(block)))
52                else:
53                    extended_text += text
54                return extended_text
55        return text