Search code examples
perltemplate-toolkit

Include on page once in Template Toolkit


using template toolkit I have come up with the below. (I am running this template multiple times on the one page.)

<table>
<tr>
    <th>Title</th>
</tr>
[% FOREACH t = Testing %]
    [% IF t.isEven %]
    <tr><td>Goodbye World</td></tr>
    [% ELSE %]
    <tr><td>hello world</td></tr>

    size() = [% loop.size %]</br>
    max () = [% loop.max %]</br>
    index () = [% loop.index %]</br>
    count () = [% loop.count %]</br>
    first () = [% loop.first %]</br>
    last () = [% loop.last %]</br>
    prev () = [% loop.prev %]</br>
    next () = [% loop.next %]</br>

    [% END %]
[% END %]
</table>
[% myJS %]

which outputs this. (i only included the first and last tr in here to save space).

<table>
    <tr>
        <th>Title</th>
    </tr>
<tr class="1"><td>hello world</td></tr>
size() = 5</br>
max () = 4</br>
index () = 0</br>
count () = 1</br>
first () = 1</br>
last () = 0</br>
prev () = </br>
next () = HASH(0x1d6daad0)</br>

<tr class="4"><td>hello world</td></tr>
size() = 5</br>
max () = 4</br>
index () = 4</br>
count () = 5</br>
first () = 0</br>
last () = 1</br>
prev () = HASH(0x1cbfda20)</br>
next () = HASH(0x1d6e9c10)</br>
</table>
<script src ="js/my.js"></script><table>

over and over until my loop is finished. Is there a way to only include [% myJS %] on the page once? as it is the same script?


Solution

  • The code that you have shown us here only displays the my.js line once. It is outside of any loop so it can't possibly be displayed more than once.

    If you're getting it displayed more than once, then you're not using the code that you are showing us. Or there is more code surrounding the code in your example. Do you perhaps have another loop which displays multiple tables?

    In general, the solution to your problem would be to move the code which displays the Javascript file outside of any loops - so it only displays once. If, however, that's not an option for some reason (and I really can't see why it wouldn't be) then you can use the loop variable to only output the Javascript on the first (or, perhaps, the last) iteration of the loop. Something like this:

    [% FOR var IN list;
         var.something_useful;
         myJS IF loop.first;
       END %]