在ZF2中如何在自定义视图助手中转义HTML

时间:2013-10-30 15:22:52

标签: view zend-framework2 escaping view-helpers zend-view

Here,我看到有人建议延长Zend\View\Helper\Escaper\AbstractHelper;,导致类似这样的内容:

namespace Photo\View\Helper;

use Zend\View\Helper\Escaper\AbstractHelper;

class Imghelper extends AbstractHelper
{
protected $_baseUrl = null;
protected $_exists = array();

public function __construct ()
{
    $url = PUBLIC_PATH;
    $root = '/' . trim($url, '/');

    if ($root == "/")
      {$root = "";}

    $this->_baseUrl = $root . "/";
}

public function escape($value)
{
   return $this->getEscaper()->escapeHtml($value);
}

public function __invoke($path, $params = array())
{
           $plist = array();
    $str = null;

    $imgpath = $this->_baseUrl . ltrim($path);

    if (!isset($this->_exists[$path]))
      {$this->_exists[$path] = file_exists(realpath($imgpath));}

    if (!isset($params['alt']))
      {$params['alt'] = '';}

    foreach ($params as $param => $value)
      {$plist[] = $param . '="' . $this->escape($value) . '"';}

            $str = " ".join(" ", $plist);
    $p = ($this->_exists[$path]) ? $this->_baseUrl.ltrim($path,'/') : null;

    if (isset($p))
      {return '<img src="'.$p.'" '.$str.' />';}
}


} 

然而,当我在我的代码中尝试它时,我得到一个错误

Strict Standards: Declaration of Application\View\Helper\Imghelper::__invoke() should be compatible with Zend\View\Helper\Escaper\AbstractHelper::__invoke($value, $recurse = 0) in ...

错误错误消息可以吗?或者有更好的方法吗?谢谢!

1 个答案:

答案 0 :(得分:1)

我不建议扩展Abstract Escape助手,因为您没有编写转义助手。坚持原来的计划,只需延长Zend\View\Helper\AbstractHelper。然后,您可以通过访问逃生助手。 $this->view->escapeHtml()$this->view->escapeJs()等等。