聪明的模板变量不清楚

时间:2013-06-14 20:25:33

标签: php e-commerce smarty

我试图了解使用PHP和smarty this is the book

开发Web应用程序

有一个文件departments_list.tpl

{* departments_list.tpl *}
{load_presentation_object filename="departments_list" assign="obj"}
{* Start departments list *}

<div class="box">
  <p class="box-title">Choose a Department</p>
  <ul>
      {* Loop through the list of departments *}
      {section name=i loop=$obj->mDepartments}
        {assign var=selected value=""}
        {* Verify if the department is selected to decide what CSS style to use *}
        {if ($obj->mSelectedDepartment == $obj->mDepartments[i].department_id)}
        {assign var=selected value="class=\"selected\""}
        {/if}
        <li>
        {* Generate a link for a new department in the list *}
        <a {$selected} href="{$obj->mDepartments[i].link_to_department}">
        {$obj->mDepartments[i].name}
        </a>
        </li>
      {/section}
  </ul>
 </div>
{* End departments list *}

我在上面的文件中不明白是

的一行
      {section name=i loop=$obj->mDepartments}

name=i如何工作我初始化的内容以及循环如何从i开始,

其次,上面的文件正在使用文件function.load_presentation_object.php

<?php
// Plug-in functions inside plug-in files must be named: smarty_type_name
function smarty_function_load_presentation_object($params, $smarty)
        {
        require_once PRESENTATION_DIR . $params['filename'] . '.php';
        $className = str_replace(' ', '',ucfirst(str_replace('_', ' ',$params['filename'])));
        // Create presentation object
        $obj = new $className();
        if (method_exists($obj, 'init'))
        {
        $obj->init();
        }
        // Assign template variable
        $smarty->assign($params['assign'], $obj);
        }
?>

在上面的文件中,参数$ params已用于最后一行

        $smarty->assign($params['assign'], $obj);

据我所知,来自文件departments_list.tpl将参数传递给function.load_presentation_object.php 如

{load_presentation_object filename="departments_list" assign="obj"}

所以当跟随被称为

function smarty_function_load_presentation_object($params, $smarty)

$ params = depratments_list和$ smarty = obj

那怎么办?             $ smarty-&gt; assign($ params ['assign'],$ obj);

在上面做什么是$ params ['assign']?

1 个答案:

答案 0 :(得分:1)

{load_presentation_object filename="departments_list" assign="obj"}

翻译成php将是:

smarty_function_load_presentation_object(
    array(
        'filename' => 'departments_list', 
        'assign'   => 'obj'
    ), 
    $smarty
);

smarty模板中指定的每个参数都在第一个参数中作为关联数组传递。第二是当前聪明的对象。

至于

{section name=i loop=$obj->mDepartments}

这是简单的for循环:

for ($i=0; $i < count($obj->mDepartments); $i++) {
    $current = $obj->mDepartments[$i];
}