Wiki

Clone wiki

poole / Home

Welcome

The following code in your `macro.py` file will enable multi-language for your poole website. If you have several hooks, make sure that it runs first (poole uses the alphabetical order of the hooks names). You need the small modification to the templates included in this repository.

import re
import itertools


def hook_preconvert_multilang():
    MKD_PATT = r'\.(?:md|mkd|mdown|markdown)$'
    _re_lang = re.compile(r'^[\s+]?lang[\s+]?[:=]((?:.|\n )*)', re.MULTILINE)
    vpages = [] # Set of all virtual pages
    for p in pages:
        current_lang = "en" # Default language
        langs = [] # List of languages for the current page
        page_vpages = {} # Set of virtual pages for the current page
        text_lang = re.split(_re_lang, p.source)
        text_grouped = dict(zip([current_lang,] + \
                                        [lang.strip() for lang in text_lang[1::2]], \
                                        text_lang[::2]))

        for lang, text in text_grouped.iteritems():
            spath = p.fname.split(os.path.sep)
            langs.append(lang)
            filename = re.sub(MKD_PATT, ".%s\g<0>" % lang, p.fname).split(os.path.sep)[-1]
            vp = Page(filename, virtual=text) 
            # Copy real page attributes to the virtual page
            for attr in p:
                if not vp.has_key(attr):
                    vp[attr] = p[attr]
            # Define a title in the proper language
            vp["title"] = p["%s_%s" % (p["title"], current_lang)] \
                                    if p.has_key("%s_%s" % (p["title"], current_lang)) \
                                    else p["title"]
            # Keep track of the current lang of the virtual page
            vp["lang"] = lang
            # Fix post name if exists
            if vp.has_key("post"):
                vp["post"] = vp["post"][:-len(lang) - 1]
            page_vpages[lang] = vp
            
        # Each virtual page has to know about its sister vpages
        for lang, vpage in page_vpages.iteritems():
            vpage["lang_links"] = dict([(l, v["url"]) for l, v in page_vpages.iteritems()])
            vpage["other_lang"] = langs # set other langs and link

        vpages += page_vpages.values()

    del pages[:] # No real page needs to be kept.
    for vpage in vpages: 
        pages.append(vpage)
       

Add tags

def hook_preconvert_tags():
  # This must be run after the multi-language hook
  from collections import Counter
  # Number of tags to show:
  num_tags = 10

  class empty_dict(dict):
    def __missing__(self, key):
      self[key] = []
      return self[key]
      
  tags = empty_dict({})
  tag_pages = empty_dict({})
  # Generated pages
  new_pages = []
  for p in pages:
    if not p.has_key("tags"): continue
    p_tags = [kw.strip().replace(" ", "_") for kw in p["tags"].split(",")]
    if not p.has_key("lang"):
      print "Page has no lang! Skipping"
      continue
    tags[p["lang"]] += p_tags
    
    # Create a dict linking tags with pages where they appear
    for tt in p_tags: tag_pages[tt].append((p["title"], p["url"], p["lang"], p["other_lang"]))

  stats = {tag_lang:Counter(tags[tag_lang]).most_common(num_tags) for tag_lang in tags.keys()}
  for lang, lang_tags in stats.iteritems():
    for tag, tag_occurence in lang_tags:
      links_tag = "\n\n".join("[%s](%s)" % (tag_item[0], tag_item[1]) \
		  for tag_item in tag_pages[tag] if tag_item[2] == lang)
      new_page = Page("tag_%s.%s.md" % (tag,lang), virtual=links_tag)
      new_page["lang"] = lang
      new_page["title"] = "%d pages for tag \"%s\"" % (tag_occurence, tag)
      new_page["other_lang"] = list(set([ii for llang in map(lambda x: x[-1], tag_pages[tag]) for ii in llang]))
      new_page["lang_links"] = dict(zip(new_page["other_lang"], \
				["tag_%s.%s.html" % (tag, lang_) for lang_ in new_page["other_lang"]]))
      new_pages.append(new_page)
      
  # add tags to each page
  tag_header = """<br/><a style='font-size:0.8em;color:gray;' href='#' onclick=\"toggle_visibility('tags');\">
  Show/hide tags</a><div id='tags' style='display:none;text-align:center;font-size:0.75em'><p>"""
  tag_footer = "</p></div>"
  for p in pages + new_pages:
    tag_names = ', '.join(["[%s](%s)" % \
	      (tt, "tag_%s.%s.html" % (tt, p["lang"])) for tt in map(lambda x:x[0], stats[p["lang"]])])
    p.source += tag_header + tag_names + tag_footer

  pages[:] = pages + new_pages

Add into pages.html:

 <script type="text/javascript">
    <!--
	function toggle_visibility(id) {
	  var e = document.getElementById(id);
	  if(e.style.display == 'block')
	      e.style.display = 'none';
	  else
	      e.style.display = 'block';
	}
    //-->
</script>

Then simply edit your foo.md files like this:

title: contact
menu-position: 6
tags: contact, info, country, whatever
---
Your contact info

lang: fr
Your contact info in french

Updated