ThinkPHP中关于Widget的小问题

左手 posted @ 2013年6月14日 21:35 in 积累点滴 with tags php TP Widget , 2655 阅读

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

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

<!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

<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模板大概是这样

<?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);。

Avatar_small
seo service london 说:
2024年2月22日 15:22

I am very happy to discover your post as it will become on top in my collection of favorite blogs to visit


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter