Skip to content

Commit

Permalink
mattrobenolt#75 Add -i --includes option that extends the paths to se…
Browse files Browse the repository at this point in the history
…arch for jinja templates

This is useful for reuse when a set of shared templates are maintained in another directory
by  using {% include 'lib/header.j2' %} style includes.
  • Loading branch information
George Spalding committed Mar 25, 2019
1 parent 7e59041 commit 5f8ea85
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 4 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,5 @@ nosetests.xml

.pytest_cache
dist/
env/
*.iml
7 changes: 6 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,20 @@ Usage: jinja2 [options] <input template> <input data>
Options:
--version show program's version number and exit
-h, --help show this help message and exit
--format=FORMAT format of input variables: auto, ini, json,
--format=FORMAT format of input variables: auto, env, ini, json,
querystring, yaml, yml
-e EXTENSIONS, --extension=EXTENSIONS
extra jinja2 extensions to load
-I INCLUDES, --includes=INCLUDES
extra jinja2 template directory to search for
(included) templates
-D key=value Define template variable in the form of key=value
-s SECTION, --section=SECTION
Use only this section from the configuration
--strict Disallow undefined variables to be used within the
template
-o FILE, --outfile=FILE
File to use for output. Default is stdout.
```

## Optional YAML support
Expand Down
13 changes: 10 additions & 3 deletions jinja2cli/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,11 +212,11 @@ def _parse_env(data):
}


def render(template_path, data, extensions, strict=False):
def render(template_path, data, extensions, strict=False, includes=[]):
from jinja2 import Environment, FileSystemLoader, StrictUndefined

env = Environment(
loader=FileSystemLoader(os.path.dirname(template_path)),
loader=FileSystemLoader([os.path.dirname(template_path)] + includes),
extensions=extensions,
keep_trailing_newline=True,
)
Expand Down Expand Up @@ -311,7 +311,7 @@ def cli(opts, args):

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

out.write(render(template_path, data, extensions, opts.strict))
out.write(render(template_path, data, extensions, opts.strict, includes=opts.includes))
out.flush()
return 0

Expand Down Expand Up @@ -378,6 +378,13 @@ def main():
action="append",
default=["do", "with_", "autoescape", "loopcontrols"],
)
parser.add_option(
"-I",
"--includes",
help="extra jinja2 template directory to search for (included) templates",
dest="includes",
action="append",
)
parser.add_option(
"-D",
help="Define template variable in the form of key=value",
Expand Down

0 comments on commit 5f8ea85

Please sign in to comment.