1

我正在学习 Kohana 3.2.0 和 KSmarty for Kohana 3。我想在页面上写一个这样的锚:

<a href="http://www.mysite.cz/page/list">Page list</a>

我可以在控制器中构建 url 并将其作为变量传递给 Smarty。有没有办法在 Smarty 模板中构建锚点或 URL(包括“http://www.mysite.cz”部分)?

如果无法构建锚。是否至少可以构建完整的 URL?

原因:我有一个包含另一个模板的主模板。 主模板将被多个控制器使用,我想避免在每个控制器中构建 URL。因此,如果 KSmarty 能够为我做这件事,我会很高兴。

4

1 回答 1

2

我找到的唯一解决方案是编写自定义函数。将以下代码保存到 Smarty 插件目录下的 function.url.php 文件中:

function smarty_function_url($params, &$smarty)
{
  $type = '';
  if(isset($params['type'])) $type = $params['type'];
  $protocol = 'http';
  if(isset($params['protocol'])) $protocol = $params['protocol'];
  $url = '';
  if(isset($params['url'])) $url = $params['url'];
  $text = '';
  if(isset($params['text'])) $text = $params['text'];

  switch($params['type'])
  {
    case 'url': 
      return Kohana_URL::site($url, $protocol);
    case 'anchor':
      $url = Kohana_URL::site($url, $protocol);    
      return "<a href='{$url}'>{$text}</a>";
    default: 
      return Kohana_URL::base('http');  
  }
}

Smarty模板中的使用示例:

{url}
{url type='url' url='admin/categories' protocol='https'}
{url type='anchor' url='admin/articles' text='List of articles'}

我必须在其中设置变量的第一个块,否则 Smarty 会生成通知“未定义的变量...”。我只是PHP学生,欢迎提出代码改进建议。

希望它会帮助其他人。

于 2012-01-22T08:18:36.000 回答