Search code examples
docpad

Generate different docpad collections for different languages


I want to tune my multilungual DocPad blog so that pages ended with *.ru.md go into /ru/ directory, and pages ended with *.en.md go into /en/ directory.

Let's say this is the initial structire

src/
  pages/
    page1.ru.md
    page1.en.md
    page2.ru.md

And this is what I want:

./
  en/
    page1.html
  ru/
    page1.html
    page2.html

./ because I am going to host with gh-pages.

And the same for posts. I would like to store them in

src/
  posts/
    post-about-docpad.ru.md
    post-about-docpad.en.md

And get

./
  en/
    posts/
      post-about-docpad.html
  ru/
    posts/
      post-about-docpad.html

How should I config docpad?


Solution

  • The 1st step is renaming your documents to use a dash for the language like so: page1-en.html, and page1-ru.html, instead of page1.en.html and page1.ru.tml — as otherwise as @kizu correctly points out, it will cause problems as DocPad renders from extension to extension.

    Once that is done, you can add the following to your docpad configuration file:

    collections:
    
        # Fetch documents in different languages
        translate: (database) ->
            languageRegex = /^(.+?)-(en|ru)$/
            #docpadOutPath = @getConfig().outPath
            @getCollection('documents').findAllLive({basename: languageRegex}).on 'add', (document) ->
                # Prepare
                a = document.attributes
    
                parts = a.basename.match(languageRegex)
                basename = parts[1]
                language = parts[2]
    
                relativeOutPath = "#{language}/#{a.relativeOutDirPath}/#{basename}.#{a.outExtension}"
                #outPath = "#{docpadOutPath}/#{relativeOutPath}"
    
                urls = ["/#{relativeOutPath}"]
    
                # Apply
                document
                    .setMetaDefaults({
                        #outPath
                        url: urls[0]
                    })
                    .addUrl(urls)
    

    This will have URLs working in the way you want.

    Then run DocPad in the static environment with the cleanurls plugin installed, to write the documents to the desired locations.

    docpad install cleanurls
    docpad generate --env static