又折腾了下Widget,纪录下遇到的两个小问题。

1.Layout中嵌入Widget,Widget未显示声明NOLAYOUT时,出现循环调用。
例:Lib/Tpl/_layout.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>这是layout</h1>
<div>
{__CONTENT__}
</div>

<div>
{:W('Test')}
</div>
</body>
</html>

Lib/Widget/Test/test.html

1
2
3
4
5
6
7
<ul>
<li><a href="javascript:;">这是Widget中的内容</a></li>
<li><a href="javascript:;">这是Widget中的内容</a></li>
<li><a href="javascript:;">这是Widget中的内容</a></li>
<li><a href="javascript:;">这是Widget中的内容</a></li>
<li><a href="javascript:;">这是Widget中的内容</a></li>
</ul>

这个时候,编译出来的Widget模板大概是这样

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>这是layout</h1>
<div>
<ul>
<li><a href="javascript:;">这是Widget中的内容</a></li>
<li><a href="javascript:;">这是Widget中的内容</a></li>
<li><a href="javascript:;">这是Widget中的内容</a></li>
<li><a href="javascript:;">这是Widget中的内容</a></li>
<li><a href="javascript:;">这是Widget中的内容</a></li>
</ul>

</div>

<div>
<?php echo W('Test');?>
</div>
</body>
</html>

Widget模板编译的时候被填充在了Layout的{__CONTENT__}中,下面W(‘test’)的Widget调用依然存在。于是发生死循环没有报错页面一片空白,逐行调试了好久才找到问题。
解决方法:在 Lib/Widget/Test/test.html 开头添加一行{__NOLAYOUT__}

2.`Widget的调用方式和传参。
我参考的是官方3.1.2的手册,手册上的示例是{:W(‘ShowComment’)},大意是调用ShowComment得到返回的内容。在 Action 中使用 $widgetContent = W(‘ShowComment’); $this->assign(‘widgetContent’,$widgetContent);但是$widgetContent的内容没有出现在模板变量{$widgetContent}出现的位置,查看函数时才看到W函数在默认情况下是echo出widget的内容。模板中正确的调法是{~W(‘ShowComment’)},如果只是要取到Widget的内容应该使用W(‘ShowComment’,array(),true);。