Skip to content

Commit a72f0f2

Browse files
committed
Add the ability to import filters
Fixes #85
1 parent de5e8bf commit a72f0f2

File tree

2 files changed

+19
-4
lines changed

2 files changed

+19
-4
lines changed

jinja2cli/cli.py

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -212,7 +212,7 @@ def _parse_env(data):
212212
}
213213

214214

215-
def render(template_path, data, extensions, strict=False):
215+
def render(template_path, data, extensions, filters, strict=False):
216216
from jinja2 import Environment, FileSystemLoader, StrictUndefined
217217

218218
env = Environment(
@@ -227,6 +227,13 @@ def render(template_path, data, extensions, strict=False):
227227
env.globals["environ"] = lambda key: force_text(os.environ.get(key))
228228
env.globals["get_context"] = lambda: data
229229

230+
if filters:
231+
from jinja2.utils import import_string
232+
233+
for filter in set(filters):
234+
filter = import_string(filter)
235+
env.filters[filter.__name__] = filter
236+
230237
return env.get_template(os.path.basename(template_path)).render(data)
231238

232239

@@ -312,7 +319,7 @@ def cli(opts, args):
312319

313320
out = codecs.getwriter("utf8")(out)
314321

315-
out.write(render(template_path, data, extensions, opts.strict))
322+
out.write(render(template_path, data, extensions, opts.filters, opts.strict))
316323
out.flush()
317324
return 0
318325

@@ -379,6 +386,14 @@ def main():
379386
action="append",
380387
default=["do", "with_", "autoescape", "loopcontrols"],
381388
)
389+
parser.add_option(
390+
"-f",
391+
"--filter",
392+
help="extra jinja2 filters to load",
393+
dest="filters",
394+
action="append",
395+
default=[],
396+
)
382397
parser.add_option(
383398
"-D",
384399
help="Define template variable in the form of key=value",

tests/test_jinja2cli.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ def test_relative_path():
1010
path = "./files/template.j2"
1111

1212
title = b"\xc3\xb8".decode("utf8")
13-
output = cli.render(path, {"title": title}, [])
13+
output = cli.render(path, {"title": title}, [], [])
1414
assert output == title
1515
assert type(output) == cli.text_type
1616

@@ -20,6 +20,6 @@ def test_absolute_path():
2020
path = os.path.join(absolute_base_path, "files", "template.j2")
2121

2222
title = b"\xc3\xb8".decode("utf8")
23-
output = cli.render(path, {"title": title}, [])
23+
output = cli.render(path, {"title": title}, [], [])
2424
assert output == title
2525
assert type(output) == cli.text_type

0 commit comments

Comments
 (0)