askama icon indicating copy to clipboard operation
askama copied to clipboard

(newb) How to pass in context to included templates

Open yatesco opened this issue 3 years ago • 4 comments

Hi - I have a common template which renders a sortable table header. In a larger template I want to call it and pass in the context (e.g. name, whether it is sorted ascending/descending).

I understand the included template has access to the context of the template it is being included in, but how do I pass in additional context.

My outer template:

        <tr>
          {% include "tableHeaderSort.html" sort='ascending' title='Open'}
          {% include "tableHeaderSort.html" sort='none' title='Closed'}
          ...

Is this possible?

Thanks!

yatesco avatar Jun 24 '21 15:06 yatesco

No, but you can macros for this instead.

djc avatar Jun 24 '21 15:06 djc

thanks @djc - let me have another read of the book to get familiar with those. Thanks :-)

yatesco avatar Jun 24 '21 15:06 yatesco

@djc How would one use macros for this - is there an example available anywhere? Or has something like Django's with keyword inside an include been implemented since this issue was reported?

OskarPersson avatar Feb 27 '22 01:02 OskarPersson

For macros you'd have to pass all the required context in explicitly, you wouldn't have access to the ambient context inside the macro as far as I remember. There's a little bit of documentation and some tests.

djc avatar Mar 23 '22 16:03 djc