Thanks to Rob's comment, I expanded the ZM2 ViewModel as follows:
namespace Application\View\Model; use Zend\View\Model\ViewModel; use Zend\View\Helper\EscapeHtml; class EscapeViewModel extends ViewModel { protected $escaper = null; public function autoEscape($autoEscape = true) { $this->options['auto_escape'] = (bool) $autoEscape; return $this; } public function __get($name) { if (!$this->__isset($name)) { return; } $variables = $this->getVariables(); if($this->getOption('auto_escape')) return $this->getEscaper()->escape($variables[$name]); return $variables[$name]; } public function getEscaper() { if (null === $this->escaper) { $this->escaper = new EscapeHtml; } return $this->escaper; } }
In the controller it can be used as follows:
public function fooAction() { return new EscapeViewModel(array( 'foo' => '<i>bar</i>' ));
Question: I would appreciate if anyone would comment on this, if this is the best practice or if there is a better one and ecp. more efficient and resource-saving way?
source share