我有一个像这样创建的按钮元素:
$submit = new Zend_Form_Element_Button('submit');
$submit->setLabel('My Button');
$submit->setDecorators(array(
'ViewHelper',
array('HtmlTag', array('tag' => 'li'))
));
$submit->setAttrib('type', 'submit');
这会生成以下 HTML:
<li>
<label for="submit" class="optional">My Button</label>
<button name="submit" id="submit" type="submit">My Button</button>
</li>
我想用一个包裹按钮的内部,像这样:
<button...><span>My Button</span></button>
使用 Zend_Form 执行此操作的最佳方法是什么?
最佳答案
我自己尝试过,但最终未能使用相同的方法实现这一目标。看起来最简单的方法是:
...
$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 脚本目录中(您最好使用 $view->addScriptPath('/path/to/my/form/decorators')
).
这应该会呈现您要查找的内容。由于我在工作中遇到的灵 active 问题,我才刚刚开始研究 ViewScript 装饰器。您会注意到我的脚本不是那么灵活,而且肯定不是 BNF 格式,因为所有成员都可以填充到元素对象上。也就是说,这是一个开始,它可以解决您的问题。
关于php - Zend 框架 Zend_Form 装饰器 : <span> Inside Button Element?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/778770/