Search code examples
pythonpelican

With Pelican, how to set or access variables between Python code and themes?


I need to pass down the original source file name (*.md file) into the sidebar.html. How can I do that?

From this site (http://pelican.readthedocs.org/en/3.6.3/themes.html), I understand some variables are available, and all capital letter variables in pelicanconf.py files are also available, but I don't know how to get the information such as the original source file in the theme files.


Solution

  • I think there might be a simpler way, but using jinja filter works fine for me ( http://linkpeek.com/blog/how-to-add-a-custom-jinja-filter-to-pelican.html)

    Steps to take:

    Pre-setup

    I make the name of the original markup file to be in the format YEAR-MONTH-DAY-NAME to be recovered from the url of the page.

    Create a filter

    The filter is given the url, and from the url, I can recover the original source md file path.

    def tosource(url):
        # example input
        # posts/2014/01/26/python-unittest-structure/index.html
        # posts/2014/01/26/ocaml-vs-java/index.html
        # posts/2014/01/25/why-ocaml-comparison-with-python/index.html
    
        if url.startswith("posts"):
            (posts, year, month, day, name) = url.split('/')[:-1]
            res = "%s/%s/%s-%s-%s-%s.md" % (year, month, year, month, day, name)
        else:
            res = "/" # implement later
        return res
    

    Update pelicanconf.py

    Teach pelican the name and location of the filter.

    import sys
    sys.path.append('.')
    
    import sourcename
    JINJA_FILTERS = {'sourcename':sourcename.tosource}
    
    OPENCONTENT = "open:///pelican/knowledge_blog/content"
    

    As is written in http://docs.getpelican.com/en/3.5.0/themes.html#theming-pelican, all capital letter variables in the conf file are accessible in the theme files.

    Update sidebar.html

    I added one line of code in sidebar.html to use the Jinja filter for getting the original md file path.

    Click to <a href="{{ OPENCONTENT }}/{{ output_file|sourcename }}">Edit</a>
    

    Generate the html

    Run make html and test.

    enter image description here enter image description here