导航中的 ZF2 自定义属性 [英] ZF2 custom attributes in navigation
问题描述
如何将自定义属性添加到 Zend Framework 2 导航中?
我知道我可以添加 id 或 class -> 但仅此而已....
How would I add custom attributes into Zend Framework 2 navigation?
I know I can add id or class -> but that's about it....
1) 例如,我将如何添加 data-test='blahblah'
属性?
2) 我可以向包含实际链接的 li
元素添加属性吗?
1) How would I add data-test='blahblah'
attribute for example?
2) Can I add attribute to li
elements that contain actual links?
$container = new Zend\Navigation\Navigation(array(
array(
'label' => 'Page 1',
'id' => 'home-link',
'uri' => '/',
),
array(
'label' => 'Zend',
'uri' => 'http://www.zend-project.com/',
'order' => 100,
),
);
@Bram Gerritsen:感谢您的回答.
@Bram Gerritsen: Thanks for your answer.
是的 - 我可以添加 'data-test' =>'blahblah'
并将其检索为 $page->get('data-test')
- 但这仍然不会将其作为属性附加到 <a></a>
.... 我是否需要将 htmlify 覆盖到那个?
Yes - I can add 'data-test' => 'blahblah'
and retrieve it as $page->get('data-test')
- but this still doesn't append it as an attribute into <a></a>
.... Would I ahve to override htmlify to to that?
推荐答案
Page 类有一些用于公共属性的专用设置器(setLabel
、setId
、setUri
等),如果 setter 不存在 __set
将被调用.请参阅手册有关这方面的更多信息以及有关扩展 AbstractPage
类的信息.
The Page classes have some dedicated setters for common attributes (setLabel
, setId
, setUri
etc), If a setter not exists __set
will be called. See the manual for more information about this and also about extending the AbstractPage
class.
array(
'label' => 'Page 1',
'id' => 'home-link',
'uri' => '/',
'data-test' => 'blahblah'
),
现在你可以执行 $page->get('data_test')
并且它会返回 blahblah.
Now you can do $page->get('data_test')
and it will return blahblah.
您的第二个问题是关于更改菜单的呈现(向 li
添加属性.ZF2 正在使用 menu view helper 渲染导航菜单.所有导航视图助手都可以选择使用您自己的局部视图来使用 setPartial()
进行渲染.
Your second question is about altering the rendering of the menu (adding a attribute to the li
. ZF2 is using the menu view helper to render a navigation menu.
All the navigation view helpers have an option to use your own partial view for rendering using setPartial()
.
在您的视图脚本中:
$partial = array('menu.phtml', 'default');
$this->navigation()->menu()->setPartial($partial);
echo $this->navigation()->menu()->render();
在你的局部视图 menu.phtml
中做这样的事情:
In your partial view menu.phtml
do something like this:
<ul>
<?php foreach ($this->container as $page): ?>
<li data-test="<?=$page->get('data_test')?>"><?=$this->navigation()->menu()->htmlify($page)?></li>
<?php endforeach; ?>
<ul>
这只会呈现菜单的最高级别.如果您有更深/嵌套的结构,您的自定义视图脚本最终会复杂得多.
This will only render the highest level of the menu. If you have deeper/nested structure your custom view script will end up far more complex.
希望这会有所帮助.
这篇关于导航中的 ZF2 自定义属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!