jinja2pelicanstatic-site

How can I use macros/variables/scripts in articles with Pelican?


I have just started with Pelican. It's awesome, I just can't figure out how to use macros in my articles (and pages). I know I can use Jinja when making my own theme, but I can't seem to be able to use it in articles. I'd like to be able to define a macro/function/template/whatever that I'd put directly in the markdown of the article, possibly with parameters, and it would get expanded when the pages are generated. For example a function to generate an image with a caption of given size and css class that would also be a link directly to the image. I'd like to be able to access these macros from all articles, to be able to reuse them everywhere. Something I'd normally do with PhP.

I could probably use JS to do this, but if I'd like to avoid it and keep everything static if possible. Can this be done?


Solution

  • UPDATE:

    I found a pelican plugin that solves this - jinja2content.


    OLD SOLUTION:

    I found a solution here. You can implement a filter in Python to process all texts in articles/pages like this:

    1. Create a python file filters.py in which you write the filter function process_text to expand my macros (or generally do anything with the article/page text), for example to test the function write something like:

       def process_text(input_text):
         return "TEST " + input_text
      
    2. In the Pelican config file (pelicanconfig.py) register this function as a possible filter to be used with Jinja:

       import sys
       sys.path.append('.')
      
       import filters
       JINJA_FILTERS = {'process_text':filters.process_text}
      
    3. Now you have to edit the templates to apply this filter to article/page texts before adding them to output. In my case I edited two files: themes/themename/templates/article.html and themes/themename/templates/post.html and changed {{ article.content }} to {{ article.content|process_text }} and {{ page.content }} to {{ page.content|process_text }} in them to apply the filter.

    Now all texts in articles and pages should be prefixed with "TEST".

    The not so convenient thing about this is I have to write my own macro expander, which shouldn't be extremely hard with regular expression in Python, but if there is a nicer way to do this, feel free to post here.