在字符串模板资源中注册 class

Register class in String Template Resource

在Smarty中,当我使用{include file="string:$template_string"}时,任何通过registerClass()在当前模板上注册的class在基于$template_string的新编译模板中不可用.有什么方法可以使在当前模板中注册的 classes 在包含的模板中也可用吗?如果我改用 {include file="eval:$template_string"} ,注册的 classes 在包含的模板中可用,但是性能影响很大,因为编译后的模板没有存储,代码在循环中。

这是一个使用两个模板文件来阐明问题的示例。 PHP 为 display.tpl 创建了一个 Smarty 模板,它扩展了 listing.tpl。 class User 注册到模板中,并为模板赋值一个数组变量$items。这些模板的目的是拥有一个通用的 table 模板,可以通过指定列标题和值的其他模板对其进行扩展。

文件:listing.tpl

{strip}{block name="properties"}{assign var="properties" value=[]}{/block}{/strip}{* extending templates should assign the variable $properties in this block *}
<table>
   <thead>
      <tr>
{foreach $properties as $property}
         <th>{$property[0]}</th>
{/foreach}
      </tr>
   </thead>
   <tbody>
{foreach $items as $item}
      <tr>
{foreach $properties as $property}
         <td>{include file="string:{$property[1]}"}</td>{* this is much faster than {include file="eval:{$property[1]}"} *}
{/foreach}
      </tr>
{/foreach}
   </tbody>
</table>

文件:display.tpl

{extends file="listing.tpl"}
{block name="properties"}
{assign var="properties" value=
   [ [_("Id"), '{$item->id}']
   , [_("Title"), '{$item->title}']
   , [_("User"), '{User::getName($item, "creator")}']
   ]
}
{/block}

我删除了所有编译的模板文件,现在可以了!似乎有些模板文件必须在注册新 class User 后重新编译,并且不会自动重新编译。所以这就是教训:如果某些东西在 Smarty 中不起作用,而您没有看到不应该起作用的原因,请尝试删除已编译的模板,也许在重新编译后它会起作用!