PageRenderTime 9ms CodeModel.GetById 1ms app.highlight 6ms RepoModel.GetById 1ms app.codeStats 0ms

/hyde/ext/plugins/languages.py

http://github.com/hyde/hyde
Python | 71 lines | 11 code | 4 blank | 56 comment | 2 complexity | aaed2ad6fbf5f6a5297ee3d868050b9c MD5 | raw file
 1# -*- coding: utf-8 -*-
 2"""
 3Contains classes to help manage multi-language pages.
 4"""
 5
 6from hyde.plugin import Plugin
 7
 8
 9class LanguagePlugin(Plugin):
10
11    """
12    Each page should be tagged with a language using `language` meta
13    data. Each page should also have an UUID stored in `uuid` meta
14    data. Pages with different languages but the same UUID will be
15    considered a translation of each other.
16
17    For example, consider that you have the following content tree:
18       - `en/`
19       - `fr/`
20
21    In `en/meta.yaml`, you set `language: en` and in `fr/meta.yaml`, you
22    set `language: fr`. In `en/my-first-page.html`, you put something like
23    this::
24         -------
25         uuid: page1
26         -------
27         My first page
28
29     And in `fr/ma-premiere-page.html`, you put something like this::
30         -------
31         uuid: page1
32         -------
33         Ma première page
34
35    You'll get a `translations` attribute attached to the resource
36    with the list of resources that are a translation of this one.
37    """
38
39    def __init__(self, site):
40        super(LanguagePlugin, self).__init__(site)
41        # Associate a UUID to the list of resources available
42        self.languages = {}
43
44    def begin_site(self):
45        """
46        Initialize plugin. Build the language tree for each node
47        """
48        # Build association between UUID and list of resources
49        for node in self.site.content.walk():
50            for resource in node.resources:
51                try:
52                    uuid = resource.meta.uuid
53                    language = resource.meta.language
54                except AttributeError:
55                    continue
56                if uuid not in self.languages:
57                    self.languages[uuid] = []
58                self.languages[uuid].append(resource)
59        # Add back the information about other languages
60        for uuid, resources in self.languages.items():
61            for resource in resources:
62                language = resource.meta.language
63                resource.translations = \
64                    [r for r in resources
65                     if r.meta.language != language]
66                translations = ",".join(
67                    [t.meta.language for t in resource.translations])
68                self.logger.debug("Adding translations for resource"
69                                  "[%s] from %s to %s" % (resource,
70                                                          language,
71                                                          translations))