Skip to content

Commit 816d698

Browse files
mattrobenoltrddimon
authored andcommitted
Add the ability to import filters
Fixes mattrobenolt#85
1 parent cc6fc7e commit 816d698

File tree

2 files changed

+19
-4
lines changed

2 files changed

+19
-4
lines changed

jinja2cli/cli.py

+17-2
Original file line numberDiff line numberDiff line change
@@ -242,7 +242,7 @@ def _load_json5():
242242
}
243243

244244

245-
def render(template_path, data, extensions, strict=False):
245+
def render(template_path, data, extensions, filters, strict=False):
246246
from jinja2 import (
247247
__version__ as jinja_version,
248248
Environment,
@@ -273,6 +273,13 @@ def render(template_path, data, extensions, strict=False):
273273
env.globals["environ"] = lambda key: force_text(os.environ.get(key))
274274
env.globals["get_context"] = lambda: data
275275

276+
if filters:
277+
from jinja2.utils import import_string
278+
279+
for filter in set(filters):
280+
filter = import_string(filter)
281+
env.filters[filter.__name__] = filter
282+
276283
return env.get_template(os.path.basename(template_path)).render(data)
277284

278285

@@ -362,7 +369,7 @@ def cli(opts, args):
362369

363370
out = codecs.getwriter("utf8")(out)
364371

365-
out.write(render(template_path, data, extensions, opts.strict))
372+
out.write(render(template_path, data, extensions, opts.filters, opts.strict))
366373
out.flush()
367374
return 0
368375

@@ -430,6 +437,14 @@ def main():
430437
action="append",
431438
default=["do", "loopcontrols"],
432439
)
440+
parser.add_option(
441+
"-f",
442+
"--filter",
443+
help="extra jinja2 filters to load",
444+
dest="filters",
445+
action="append",
446+
default=[],
447+
)
433448
parser.add_option(
434449
"-D",
435450
help="Define template variable in the form of key=value",

tests/test_jinja2cli.py

+2-2
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)