【问题标题】:How to include helpers in smarty?如何在 smarty 中包含助手?
【发布时间】:2010-12-01 20:46:18
【问题描述】:

我喜欢在 smarty 模板中使用来自助手的静态函数。我正在使用 ko3 和 kohana-module-smarty - https://github.com/MrAnchovy/kohana-module-smarty/ 所以我的问题是如何自动加载帮助程序并在模板中使用它,即:

app/class/url.php


类网址{
函数测试 () {
返回“测试”;
}
}


views/index.tpl


{$url.test}

【问题讨论】:

  • 你应该已经添加了'php'标签

标签: php kohana smarty helpers


【解决方案1】:

您应该能够将Url 作为变量$url 传递,并在您的视图中使用{$url->test()} 访问它。我不确定您是否能够访问像 Url::test() 这样的静态函数。

如果您在相同的视图中使用帮助器,您可以创建一个新的控制器来绑定视图中的变量:

<?php
// application/classes/controller/site.php
class Controller_Site extends Controller_Template
{
    public $template = 'smarty:my_template';

    public function before()
    {
        $this->template->set_global('url_helper', new Url);
    }
}
?>

然后在你的其他控制器中扩展它:

<?php
// application/classes/controller/welcome.php
class Controller_Welcome extends Controller_Site
{
    public function action_index()
    {
        $this->template->content = 'Yada, yada, yada...';
    }
}

并在您的视图中访问它:

{* application/views/my_template.tpl *}
<p>This is a {$url_helper->test()}.</p>
<p>{$content}</p>

【讨论】:

  • 刚刚遇到这个,只是想确认上面的答案是正确的,并解释为什么在模板引擎中访问静态方法是不合适的——它破坏了沙盒。如果你真的想在你的模板中允许{Kohana::config('database.default.connection.password')},你可以写一个插件来做到这一点:)
猜你喜欢
  • 2020-03-10
  • 1970-01-01
  • 2010-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-26
  • 1970-01-01
  • 2020-04-24
相关资源
最近更新 更多