Created
December 4, 2020 01:09
-
-
Save ryxcommar/77534a9e8d5f2161cd6c94031a16d7ec to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""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