我已经尝试过,但最终未能使用相同的方法自己实现这一目标。似乎最简单的方法是这样做:
...
$submit->setLabel('<span>My Button</span>');
...
但是,跨度将被转义。完全可以关闭标签装饰器的转义,但是,添加标签装饰器会错误地呈现输出,例如:
$decorator = array(
array('ViewHelper'),
array('HtmlTag', array('tag' => 'li')),
array('Label', array('escape' => false))
);
$submit = new Zend_Form_Element_Button('submit');
$submit->setLabel('<span>My Button</span>');
$submit->setDecorators($decorator);
$submit->setAttrib('type', 'submit');
...呈现:
<label for="submit" class="optional"><span>My Button</span></label>
<li>
<button name="submit" id="submit" type="submit"><span>My Button</span></button>
</li>
...除了在语义上不正确(易于修复)之外,它仍在转义元素内的 span 标签。
所以你会怎么做?
好吧,我认为最好的方法(当涉及到对 Zend_Form 渲染的严格控制时,这是我的元建议)是使用ViewScript装饰器。
$submit = new Zend_Form_Element_Button('submit');
$submit->setLabel('My Button');
$submit->setDecorators(array(array('ViewScript', array('viewScript' => '_submitButton.phtml'))));
$submit->setAttrib('type', 'submit');
...然后在_submitButton.phtml中定义以下内容:
<li>
<?= $this->formLabel($this->element->getName(), $this->element->getLabel()); ?>
<button
<?php
$attribs = $this->element->getAttribs();
echo
' name="' . $this->escape($this->element->getName()) . '"' .
' id="' . $this->escape($this->element->getId()) . '"' .
' type="' . $this->escape($attribs['type']) . '"';
?>
<?php
$value = $this->element->getValue();
if(!empty($value))
{
echo ' value="' . $this->escape($this->element->getValue()) . '"';
}
?>
>
<span>
<?= $this->escape($this->element->getLabel()); ?>
</span>
</button>
</li>
_submitButton.phtml文件需要位于视图脚本目录中(您最好使用 为您的表单装饰器添加一个特定的目录)$view->addScriptPath('/path/to/my/form/decorators')
。
这应该呈现您正在寻找的内容。由于我在工作中遇到的灵活性问题,我才刚刚开始研究 ViewScript 装饰器。您会注意到我的脚本不是那么灵活,而且肯定不在 BNF 中,因为元素对象上可以填充所有成员。也就是说,这是一个开始,它可以解决您的问题。