add_JinjaFilter

EditFrontMatter.add_JinjaFilter(name, func, *args, **kwargs) → None[source]
Add a Jinja filter

for setting a jinja2 template variable programmatically through callback.

Parameters
  • name (str) – Jinja template variable name

  • func (object) – callback function that will set name

Example of implementing a filter for callback

Programatically change the value of draft field in the source document example1.md using a Jinja2 filter

jinja2 template

{% set toc = "true" %}

toc: {{ toc }}
draft: {{ false | canPublish }}
hasMath: {{ hasMath }}
stuff: {{ addedVariable }}
mardown file

---
title: "EditFrontMatter Class Example 1"
description: "Edit some fields in this front matter"
catagories: [programming, python, markdown]

deleteme: this will be deleted

tags: [front matter, administration, testing]

# comments and spaces will be eliminated (see docs)

author: "Karl N. Redman"
creatordisplayname: "Karl N. Redman"
creatoremail: "karl.redman@example.com"
date: 2019-05-23T17:43:45-05:00
lastmodifierdisplayname: "Karl N. Redman"
lastmodifieremail: "karl.redman@gmail.com"
lastmod: 2019-05-23T17:43:45-05:00
toc: false
type: "page"
hasMath: false
draft: false
weight: 5
---

# EditFontMatter Class Example 1

Edit several fields of front matter.

## Fields affected in this example:

* toc
  * note: uses local template variable
  * pre: false
  * post: true
* draft:
  * note: uses jinja2 filter (callback)
  * pre: false
  * post: true
* hasMath
  * note: uses program variable
  * pre: true
  * post: false
* stuff:
  * note: uses program variable to create field
  * pre: did not exist
  * post: (list) ['one', 'two', 'three']
* deleteme:
  * note: removed from final result
  * pre: this will be deleted
  * post: N/A
Example code

from editfrontmatter import EditFrontMatter
import os

# a jinja2 filter callback function
def canPublish_func(val):
    # do some processing....
    return True

# stringify the template file
template_str = ''.join(open(os.environ.get("TEST_DATA_DIR") +
    "template1.j2", "r").readlines())

# creating object
obj = EditFrontMatter(file_path = os.environ.get("TEST_DATA_DIR") + "example1.md",
        template_str = template_str)

# set `canPublish_func` function for our `draft` field callback using
# `canPublish` template variable.
obj.add_JinjaFilter('canPublish', canPublish_func)

# process the front matter from 'example1.md'. `draft` in the front
# matter will be set to `true`
obj.run()

# print the new file contents (uncomment to see dump)
# print(obj.dumpFileData())