tardyp / sphinx-jinja

MIT License
28 stars 22 forks source link

Custom/New filters #15

Open vancheese opened 3 years ago

vancheese commented 3 years ago

Is it possible to add custom/new filters? If so, where/how would you define them in conf.py

vancheese commented 3 years ago

https://stackoverflow.com/questions/10632232/adding-a-custom-filter-to-jinja2-under-pyramid suggests


from jinja2 import Environment

#Define a new filter
def GetBitValue(num,place):
    y = (num >> (place-1)) & 1
    return y

env = Environment()
env.filters['getbitvalue'] = GetBitValue

This approach seems to be quite valid but where should this be placed so that sphinx know about it... (the conf.py doesn't work)

flying-sheep commented 3 years ago

Not really, but you can hack it in:

from functools import wraps
import sphinx.ext.autosummary.generate as gen
import sphinxcontrib.jinja
from jinja2 import Environment

class AutodocEnv(Environment):
    @wraps(Environment.__init__)
    def __init__(self, *args, **kw):
        super().__init__(*args, **kw)
        from sphinx.util import rst
        self.filters['escape'] = rst.escape
        self.filters['e'] = rst.escape
        self.filters['underline'] = gen._underline

sphinxcontrib.jinja.Environment = AutodocEnv
vancheese commented 3 years ago

Wooh, awesome reply I solved the problem by adding a custom filter dictionary in the conf file and then adding it during the templating process See it on my fork - https://github.com/vancheese/sphinx-jinja

tardyp commented 3 years ago

@vancheese I'd be happy to include in the main repo and release a new version. Please submit a PR! :)