What would be the appropriate equivalent of Jinja macros in the Django template system?

Let's say that I need to display a certain amount of HTML over and over on the page, for example, for user profile information. Jinja macros seem to be absolutely suitable for such use. However, Django has no macros.

I am currently using a custom filter for the same purpose - is this the best way to do this, or am I missing something?

Thanks.


ps. I am porting an application that runs on GAE using webapp2 and Jinja in Django.

+6
source share
4 answers

After I removed the documentation a bit more, I finally found the β€œright” way to do this: custom inclusion tags that allow you to create a tag from a template.

+7
source

There are two other approaches you could take: blocks and includes . With blocks, you would have to include it completely through the inheritance chain. With inclusion, you simply boot as needed, but you need to make sure that you pass the appropriate context variables from your view. However, your current approach is probably most useful in terms of DRY.

+2
source

Django has no macros, so it either adjusts the filters or separates your repeating code in its own template, and turns it on again and again with different arguments passed through "c", which will probably work more slowly than macros. But you can really use jinja2 template system with django perfectly.

+1
source

Just for the record, I really spent quite a bit of time adapting a pre-existing snippet to make macros in django in a fairly reliable way, if you really want macros, please check it out .

As a tip, most of the time what you want to do with a macro you should really do with the include tag, as mentioned above; however, sometimes you just need a macro, and for this you need to use a template tag library such as my (which is one of the few that do this for django).

0
source

Source: https://habr.com/ru/post/911103/


All Articles