sponsfreixes / jinja2-fragments

Render Jinja2 template block as HTML page fragments on Python web frameworks.
MIT License
228 stars 12 forks source link

CSS selectors #31

Open sabr-math opened 2 months ago

sabr-math commented 2 months ago

I haven't used Flask and Jinja for a long time and just stumbled upon this project via the htmx website. So maybe my suggestion doesn't make much sense. But here it is:

Have you considered using CSS selectors in a render_ function instead of (or in addition to) marking the blocks explicitly with {%block%} and `{%endblock%} in the template and giving them a label?

That would provide way more flexibility, but only work for html. It would also now be unclear that this template is being depended on (and how), but maybe this drawback is acceptable or could otherwise be mitigated.

stfnx commented 1 month ago

This makes perfect sense and would allow targeting elements with super high precision. I think this could be a cool addition.

sponsfreixes commented 1 month ago

It's an interesting idea, and given that the core is getting fragments out of a template, initially I would say it's a good request for jinja2-fragments.

On the other hand, the implementation would be very different from how jinja2-fragments is currently working. Right now it's leveraging jinja blocks, which jinja is already able to "chop". For CSS selectors, we would need to rely on some dependency (if any exists) to extract the fragment. And following this train of thought, at this point we don't even care if it's a jinja template or some other template format. Which makes me wonder if having a separate library (css-fragments?) would be more appropriate.

Then, one could extract the fragment using the CSS selector, and then pass that fragment to their template engine of choice.

I'll leave the issue open for now as I thinks it's an interesting conversation to follow.

stfnx commented 1 month ago

"css-fragments" would be a misleading name imo. If you really wanted to implement this functionality, one option would be to rename the project from Jinja2-Fragments to HTML-Fragments and offer different selection methods: jinja, css, html id

Something like BeautifulSoup would provide the necessary tools to select by both css and id. But at this point, one could use BeautifulSoup directly instead of this library.

sponsfreixes commented 1 month ago

Oh, with my comment I didn't mean to rename jinja2-fragments, but to build that functionality on a new library. As you suggest, HTML fragments would probably be a better name for that.

I'm not familiar enough with BeautifulSoup to assess if that new library would make sense, though, if BeautifulSoup is already very easy to use in the way described above.