-2

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?

4

1 回答 1

1

您在此处向我们展示的代码仅显示 my.js 行一次。它在任何循环之外,因此不可能多次显示。

如果您多次显示它,那么您没有使用您向我们展示的代码。或者您的示例中的代码周围有更多代码。您是否可能有另一个显示多个表格的循环?

通常,您的问题的解决方案是将显示 Javascript 文件的代码移到任何循环之外 - 所以它只显示一次。但是,如果由于某种原因这不是一个选项(我真的不明白为什么不会这样),那么您可以使用循环变量仅在第一次(或者,也许是最后一次)迭代时输出 Javascript的循环。像这样的东西:

[% FOR var IN list;
     var.something_useful;
     myJS IF loop.first;
   END %]
于 2012-07-24T12:24:16.050 回答