ThinkPHP - 自定义标签库 - 标签驱动

ThinkPHP 官方文档:http://document.thinkphp.cn/manual_3_2/taglib_driver.html

创建一个类,继承自TagLib类:

<?php
/**
 * 自定义标签库
 */Class TagLibHf extends TagLib {
    //接收标签
    Protected $tags = array(
        'nav' => array(
            'attr' => 'order',
            'close' => 1
        ),
    );

    Public function _nav($attr, $content) {
        $arr = $this->parseXMLAttr($attr, 'nav');

        $str = <<<str
<?php
    \$_nav_cate = M('Cate')->order("{$arr['order']}")->select();
    import('Class.Category', APP_PATH);
    \$_nav_cate = Category::mergeCateToTwoArray(\$_nav_cate);
    foreach( \$_nav_cate as \$_nav_cate_v ) :
        extract( \$_nav_cate_v );
    \$url = U('/c_' . \$id);/*生成URL*/
?> str; $str .= $content; $str .= '<?php endforeach; ?>'; return $str; } }

上面的代码最终生成的php代码:

<?php
 $_nav_cate = M('Cate')->order("sort")->select(); import('Class.Category', APP_PATH); $_nav_cate = Category::mergeCateToTwoArray($_nav_cate); foreach( $_nav_cate as $_nav_cate_v ) : extract( $_nav_cate_v ); ?><li class='nav-lv1-li'>
                    <a href="" class='top-cate'><?php echo ($name); ?></a>
                    <ul>
                        <?php if(is_array($child)): foreach($child as $key=>$v): ?><li><a href=""><?php echo ($v["name"]); ?></a></li><?php endforeach; endif; ?>
                    </ul>
                </li><?php endforeach; ?>

 

 

 

前台代码(部分):

<div class='top-nav-wrap'>
    <ul class='nav-lv1'>
        <li class='nav-lv1-li'>
            <a href="" class='top-cate'>博客首页</a>
        </li>

        <nav order="sort">
            <li class='nav-lv1-li'>
                <a href="<{$url}>" class='top-cate'><{$name}></a>
                <ul>
                    <foreach name="child" item="v" >
                        <li><a href="<{:U('/c_' . $v['id'])}>"><{$v.name}></a></li>
                    </foreach>
                </ul>
            </li>
        </nav>
        
    </ul>
</div>

 

 

 

开启配置文件:

<?php
return array(
    'APP_AUTOLOAD_PATH' => '@.TagLib',
    'TAGLIB_BUILD_IN' => 'Cx,Hf'
);

 

你可能感兴趣的:(ThinkPHP - 自定义标签库 - 标签驱动)