在String Template Resource

时间:2015-05-19 09:56:29

标签: smarty

在Smarty中,当我使用{include file="string:$template_string"}时,基于$template_string的新编译模板中无法通过registerClass()在当前模板上注册的任何类。有没有办法让在当前模板中注册的类也可以在包含的模板中使用?如果我使用{include file="eval:$template_string"}代替,已注册的类在包含的模板中可用,但性能影响很大,因为编译的模板未存储且代码处于循环中。

以下是使用两个模板文件澄清问题的示例。 PHP为display.tpl创建了一个Smarty模板,扩展了listing.tpl。类User已注册到模板,并且数组变量$items已分配给模板。模板的目的是拥有一个通用表模板,可以通过指定列标题和值的其他模板进行扩展。

档案: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}

1 个答案:

答案 0 :(得分:0)

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