heisersch has asked for the wisdom of the Perl Monks concerning the following question:

Hi,
i would like to include TT code containing in a variable in a Template Toolkit. And don't know how to do it.
I use Catalyst and would do somthing like this:
$c->stash( foo => 'text [% any(code) %]...'); #in my case foo comes from DB

and then in .tt include this like a file
... [ % INCLUDE foo % ] ...
how can i do this?

Thanks
Heisersch

Replies are listed 'Best First'.
Re: Include code in Template Toolkit
by locked_user sundialsvc4 (Abbot) on Jan 11, 2012 at 15:30 UTC

    I believe that all you need to do here is to just specify the variable, i.e.:   [% foo %].

    After all, from TT’s point of view, you aren’t “INCLUDEing” another template-file.   You’re just inserting the contents of a Perl variable (or function, what have you) into the output stream.   The fact that this variable happens to contain HTML is of no interest to TT, and the web-browser will not be able to tell the difference.

    The only thing that you have to be aware of (and please note that I have not worked with Catalyst in quite some time) is how to present the variable to TT in such a way that it, one way or another, represents a value withdrawn from the “stash.”   Bear in mind that a TT “variable” can correspond to a Perl function (a “closure,” to use the fancy-pants computer science term), such that when TT encounters it, TT will see that it corrsponds to a code-ref, and therefore will call that function and use its result.   Very handy sometimes.   The concept might be useful here, or, as the case may be, it might be overkill, but it’s a very good feature of TT to be aware of.

      thanks for the answer
      but my foo variable contains TT code that should be rendered and not just pasted
      like:
      my $foo = 'text ... [% TTcode %] ... text';
        I don't think that will work. The TT-engine will not recursively re-apply itself in order to resolve "new" TT-code that the present compilation level has introduced.

        You will have to feed your $foo to the TT-engine again (and again and ...) until all the TT-tags are processed.

        CountZero

        A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James