Smarty模板继承的实现方法

风行水上 @ 2014-11-23 23:11:21
标签:

    Smarty模板的继承示例:

    {extends 'parent.tpl'}
    
    {block name='main'}
    ... override content in parent ...
    {/block}
    

    Smarty模板的编译

    • 先解析子模版
    • 后解析父模版
    File: libs/sysplugins/smarty_internal_templatecompilerbase.php
    
    function compileTemplate(...){
      ...
      while($this->template->source = array_shift($this->sources)){
         ... ...
      }
      ...
    }
    

    Smarty模板{extends}的编译

    • 将父模版加入到待编译模版代码序列中
    • 将当前模版设置为继承模式
    # File: libs/sysplugins/smarty_interal_compile_extends.php
    
    function compileTemplate(...){
      array_unshift($compiler->sources, $_template->source);
      $compiler->inheritance_child = true;
    }
    

    Smarty模板{block}的编译

    • 如果是子模版,则先缓存模板代码
    • "{block}"被替换为"{private_child_block}"
    • 直到父模版的"{/block}"时才会触发相应的子模版中"{block}"模版的编译,并生成最终编译代码
    • 子模版中"{block}"的编译由函数Smarty_Internal_Compile_Block::compileChildBlock()负责
    # File: libs/sysplugins/smarty_interal_compile_block.php
    
    if($compiler->inheritance_child){
       self::$block_data[$name]['source']  = "{private_child_block name='$name'}";
       self::$block_data[$name]['source'] .= "{/private_child_block}";
       return;
    } else {
      $output = Smarty_Internal_Compile_Block::compileChildBlock($compiler, $name);  
    }
    

    {$smarty.block.parent}的编译

    {$smarty.block.parent}会被简单地替换为点位符__SMARTY_BLOCK_PARENT__

    {$smarty.block.child}的编译

    {$smarty.block.child}也会触发相应的compileChildBlock()的操作。

    compileChildBlock()的任务

    Smarty_Internal_Compile_Block::compileChildBlock()的任务主要是编译字符串形式的模版源代码,并和父模版中的相应"{block}"进行合并。

    子模版和父模版合并时的关系主要是

    • $smarty.block.parent: 通过替换占位符__SMARTY_BLOCK_PARENT__来实现
    • prepend
    • append
    • 替换

    其它阅读

    标签:

      分享到:
      comments powered by Disqus

      25/27ms