Skip to content
This repository has been archived by the owner on Dec 17, 2024. It is now read-only.

feat: custom extension support simply pass in code #9

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

ImSingee
Copy link
Contributor

The extension is a good feature. But now we can only use some "built-in" extension.

In this PR, I extend the semantics for the Extensions config so that users can also write code directly to use custom extensions.

@codablock
Copy link
Contributor

I wonder if it wouldn't be better to have some generic code for Environment initialisation and then use that to actually modify the environment to have custom filters/extensions. For example:

j2.RenderString("test - {{ test_var1 | minus(-2) }}", WithInitEnvironment(`
def add(a, b):
    return int(a) + int(b)

def init_environment(environment):
    from jinja2.ext import Extension
    class DemoExtension(Extension):
        def __init__(self, environment):
            super().__init__(environment)
            environment.filters['minus'] = self.minus
            
        @staticmethod
        def minus(a, b):
            return int(a) - int(b)
    environment.add_extension(DemoExtension)
    environment.filters["add"] = add
`))

This would allow arbitrary initialisation of the environment. Based on that, you could then modify WithFilter and WithExtension to simply call WithInitEnvironment but with pre-generated python code, so that these functions are just wrappers/helpers around WithInitEnvironment.

build_env would then simply exec all the init_environments entries and look for the init_environment method and just call it.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants