Skip to content

Instantly share code, notes, and snippets.

@ryxcommar
Created December 4, 2020 01:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryxcommar/77534a9e8d5f2161cd6c94031a16d7ec to your computer and use it in GitHub Desktop.
Save ryxcommar/77534a9e8d5f2161cd6c94031a16d7ec to your computer and use it in GitHub Desktop.
"""Run this file like this:
>>> python jinja_cli.py path/to/my/file.txt --foo bar
and it will render the file as a Jinja template with foo="bar".
"""
import os
import click # pip install click
import jinja2 # pip install jinja2
JINJA_DIRECTORY = os.path.dirname(__file__)
jinja_env = jinja2.Environment(
loader=jinja2.FileSystemLoader(JINJA_DIRECTORY)
)
@click.command(context_settings=dict(
ignore_unknown_options=True,
allow_extra_args=True
))
@click.argument('filename', type=click.Path(exists=True))
@click.pass_context
def generate_markup(ctx: click.Context, filename: str):
"""Markup a file with Jinja and print the results.
This command accepts arbitrary args that start with two dashes, e.g.
`--foo bar` passes foo="bar" into the Jinja template.
"""
# Parse extra options
iterargs = iter(ctx.args)
kwargs = {k[2:]: v for k, v in zip(iterargs, iterargs)}
# render template
res = jinja_env.get_template(filename).render(**kwargs)
# print the file into the terminal
click.echo(res)
if __name__ == '__main__':
generate_markup()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment