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
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions jinja2_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,21 @@ def multiply(a, b):
`))
assert.NoError(t, err)
assert.Equal(t, "test - 6", s)

s, err = j2.RenderString("test - {{ test_var1 | minus(-2) }}", WithExtension(`
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)
`))
assert.NoError(t, err)
assert.Equal(t, "test - 3", s)
}

type testStruct struct {
Expand Down
4 changes: 4 additions & 0 deletions opts.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,10 @@ func WithFilter(name string, code string) Jinja2Opt {
}
}

// WithExtension adds a custom extension to the engine
//
// You can pass in an import path to an extension (for using some built-in extension, e.g. `jinja2.ext.debug`)
// Or you can pass in the code of an extension (there must be exactly one class inherited from `jinja2.ext.Extension`)
func WithExtension(e string) Jinja2Opt {
return func(o *jinja2Options) {
o.Extensions = append(o.Extensions, e)
Expand Down
16 changes: 15 additions & 1 deletion python_src/go_jinja2/jinja2_renderer.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from jinja2 import StrictUndefined, ChainableUndefined, ChoiceLoader
from jinja2.ext import Extension

from .jinja2_utils import MyEnvironment, extract_template_error, RootTemplateLoader, SearchPathAbsLoader, \
MyFileSystemLoader
Expand Down Expand Up @@ -42,7 +43,20 @@ def build_env(self):
environment.globals.update(self.opts.get("globals", {}))

for e in self.opts.get("extensions", []):
environment.add_extension(e)
e = str(e)
if e.count("\n") == 0: # single line, assume it's a module name
environment.add_extension(e)
else: # multi line, assume it's python code
track = {}
exec(e, track)
k = None
for v in track.values():
if isinstance(v, type) and v != Extension and issubclass(v, Extension):
k = v
break
if k is None:
raise AttributeError("No Extension subclass found in code")
environment.add_extension(k)

for name, code in self.opts.get("filters", {}).items():
track = {}
Expand Down