pallets / jinja

A very fast and expressive template engine.
https://jinja.palletsprojects.com
BSD 3-Clause "New" or "Revised" License
10.33k stars 1.62k forks source link

Allow `Environment.from_string()` to take a filename for the loaded template #2013

Closed bartfeenstra closed 2 months ago

bartfeenstra commented 2 months ago

I currently use Environment.from_string() to dynamically load template files, and I would like to be able to set the correct file name on them so the generated tracebacks are much more helpful in identifying the source file (rather than the tracebacks saying the file was <template>). The reason I am not using a Loader is twofold: none of these files ever need to be rendered twice, and Loader is blocking (i.e. not async).

Please look at the PR as an example of the approach itself. If you think this is something that would be approved, I'll finish up the tests and documentation.

To do

davidism commented 2 months ago

As explained in https://github.com/pallets/jinja/issues/1316, we don't plan to add this.

bartfeenstra commented 2 months ago

Thanks for clarifying this. I do think this is a needless restriction, especially considering https://github.com/pallets/jinja/issues/1304 has not been worked on (I get it, we're all busy, this is not a criticism). Switching to loaders, while possible, would add some unneeded blocking file I/O to my application, just to get a better hint in the traceback.

davidism commented 2 months ago

There's another option offered in the issue I linked, which does allow setting the filename.

I don't know your exact circumstance, but I wouldn't expect loading the template to be a significant length of blocked time. You could also use a thread executor if it was an issue: https://docs.python.org/3/library/asyncio-task.html#running-in-threads

has not been worked on (I get it, we're all busy, this is not a criticism)

Thanks for understanding. I'm always happy to review a good design or PR! I don't personally use asyncio, so waiting for me to do something about it is going to take a lot longer, compared to someone who needs and understands asyncio contributing to the project.

bartfeenstra commented 2 months ago

I admit I completely missed that one suggestion earlier, but I'm happy to report that I successfully implemented it in https://github.com/bartfeenstra/betty/pull/1861.

Thanks for your time and work on Jinja! 😊