diff --git a/README.md b/README.md index a74334f..28f0ca9 100644 --- a/README.md +++ b/README.md @@ -4,13 +4,23 @@ Every now and then, it's pretty useful to just have a cli tool that does the job ## Usage: ## ``` -python j2-lint.py my-template.j2 +python j2lint.py my-template.j2 ``` It accepts multiple arguments so shell expansion and/or combining with find is no issue: ``` -python j2-lint.py *.j2 -find src -type f -name "*.j2" -exec python j2-lint.py '{}' + +python j2lint.py *.j2 +find src -type f -name "*.j2" -exec python j2lint.py '{}' + ``` +## Usage with custom filters, tests, etc ## + +If you want to use this linter with custom filters, tests, etc, you can easily +extend the main cli endpoint by passing in a `env` keyword argument. + +The file [custom_check_example.py](custom_check_example.py) provides a working example for the filter +'to_nice_json'. + +Note that for linting it is not necessary to refer to the actual implementation +of the filters, jinja2 only needs to know they exist. diff --git a/custom_check_example.py b/custom_check_example.py new file mode 100644 index 0000000..c64f26a --- /dev/null +++ b/custom_check_example.py @@ -0,0 +1,13 @@ +""" +This is an example of how to extend the default environment +and/or loader to add your own filter logic. +""" +import jinja2 +from j2lint import main, AbsolutePathLoader + +filters = ['to_nice_json'] + +env = jinja2.Environment(loader=AbsolutePathLoader()) +env.filters.update({name: lambda: None for name in filters}) + +main(env=env) diff --git a/j2-lint.py b/j2lint.py similarity index 79% rename from j2-lint.py rename to j2lint.py index ad51457..1a3c6fa 100644 --- a/j2-lint.py +++ b/j2lint.py @@ -1,5 +1,5 @@ """ -@author Gerard van Helden +@author Gerard van Helden @license DBAD, see Simple j2 linter, useful for checking jinja2 template syntax @@ -19,9 +19,7 @@ def get_source(self, environment, path): return source, path, lambda: mtime == os.path.getmtime(path) -def check(template, out, err): - env = jinja2.Environment(loader=AbsolutePathLoader()) - +def check(template, out, err, env=jinja2.Environment(loader=AbsolutePathLoader())): try: env.get_template(template) out.write("%s: Syntax OK\n" % template) @@ -33,11 +31,13 @@ def check(template, out, err): err.write("%s: Syntax check failed: %s in %s at %d\n" % (template, e.message, e.filename, e.lineno)) return 1 - -if __name__ == "__main__": +def main(**kwargs): import sys - try: - sys.exit(reduce(lambda r, fn: r + check(fn, sys.stdout, sys.stderr), sys.argv[1:], 0)) + sys.exit(reduce(lambda r, fn: r + check(fn, sys.stdout, sys.stderr, **kwargs), sys.argv[1:], 0)) except IndexError: - sys.stdout.write("Usage: j2-lint.py filename [filename ...]\n") + sys.stdout.write("Usage: j2lint.py filename [filename ...]\n") + +if __name__ == "__main__": + main() +