jinja_partials
jinja_partials copied to clipboard
Without Flask
Hello, I'm working with a number to html templates which need to be used both online and offline. Is there anyway for this library to work in html outside of Flask? Thank you
Hi @Snicker7 That's a great use-case. I've done this for email templates, pdfs, and others. Basically, you'd just need to do what is happening here:
def register_extensions(app: 'Flask'):
if flask is None:
raise PartialsException('Install Flask to use `register_extensions`')
app.jinja_env.globals.update(render_partial=generate_render_partial(flask.render_template))
But without Flask's app, and use a different render function. Just add render_partial as data available to the Jinja template.
One way to do that would be to simply send a value for render_partial
that is a function which when provided a template and data, would render it. I think you should be able to manage that pretty easily with what you're doing now.
Thanks for the helpful comment @mikeckennedy! @Snicker7 and I are working on this together.
Here is what we came up with and seems to work.
def render_template(template_name, jinja2_env, **data):
"""Render a template with partials.
Parameters
----------
template_name: str
The name of the template to render. For example, if you have a template
file called `templates/my_template.html` you would pass in
`my_template.html`.
jinja2_env: jinja2.Environment
The Jinja2 environment being used.
**data: keyword arguments of any type
Additional keyword arguments that are passed to the template.
Returns
-------
The rendered template.
"""
def custom_partial_render(partial_template_name, **partial_data):
template = jinja2_env.get_template(partial_template_name)
partial_data.update(
render_partial=jinja_partials.generate_render_partial(
custom_partial_render,
),
)
return template.render(**partial_data)
return jinja_partials.render_partial(
template_name, custom_partial_render, **data,
)
Would a PR with something like this in the README.md be useful? Or in the library itself? If not, that is totally fine.
Thanks again for your help and this library!
For me it was absolutely useful! I mean its kind of trivial, but i kind of expected be able to use a simple jinja2 environment without flask/fastapi with this extension. So +1 from me
Hey all. @Colelyman Yes, a PR for that would be welcome. Can you add a test to make sure it works and keeps working?
I agree that Jinja without Flask is very useful. For things like FastAPI but also for just using templates outside of web requests. I've done it for PDF files for example. Thank you!
This is now published to PyPI as 0.2.0, thanks to the PR by @sam-kleiner https://pypi.org/project/jinja_partials/0.2.0/ :)