Search code examples
template-toolkit

Template Toolkit: evaluating template statements inside a WRAPPER block?


Alright, I have looked over the manual for more than two hours now, also tried to find a solution in the badger book, but couldn't come up with anything that works.

The following is the wrapper (body.tt), well you get the idea:

[%- PROCESS 'const.tt' -%]
<?xml version="1.0" encoding="utf-8"?>
Loads of HTML
[%- content -%]
More HTML

The wrapped templates look like this:

[% WRAPPER 'body.tt' %]
Other HTML
[%- bar -%]
More other HTML
[% END %]

And finally const.tt looks like this:

[% bar = 'foo' %]

... and for some reason the instance of bar inside the wrapped template does not get evaluated. Any ideas how I could get that evaluated?

I have tried:

[%- content | eval -%]

... which did not work.

Note, that in the wrapped template (2nd block above) I want to be able to evaluate the variable bar from const.tt without having to add another PROCESS 'const.tt' to that template. After all the variable should be available from body.tt.

And I forgot to mention: Template Toolkit version 2.22


Solution

  • Here is why what you tried doesn't work.

    As http://template-toolkit.org/docs/manual/Directives.html#section_WRAPPER explains, your wrapped content is evaluated first, and then body.tt is processed with the already evaluated template passed in as content. Therefore content is finished before content.tt is loaded.

    That said, there is a way to do it, but it is a little ugly. Here is your content:

    %- PROCESS 'body.tt' -%]
    [%- WRAPPER body -%]
    Other HTML
    [%- bar -%]
    More other HTML
    [% END %]
    

    Here is body.tt:

    [%- PROCESS 'content.tt' -%]
    [% BLOCK body -%]
    <?xml version="1.0" encoding="utf-8"?>
    Loads of HTML
    [%- content -%]
    More HTML
    [% END -%]
    

    And content.tt did not change:

    [% bar = 'foo' %]
    

    While this works, I make no promises about the sanity of the person who has to maintain it later.