Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
970 views
in Technique[技术] by (71.8m points)

tp5 不能嵌套使用模板变量么?

新手学习tp5
有两个表
teacher:id name username
klass:id name teahcer_id

现在需要在模板页面循环输出klassd的内容,其中,希望把klass里面的teacher_id转换成teacher里面的name来显示。

正常情况下:
$klass->teahcer_id 返回的是id
如果想得到是teacher.name 必须再去查teacher

用klass的字段作为查询条件,放到teacher里面去查询name.
想到的是封装成一个函数:

public function getTeacher($teacher_id){
$teacher = TeacherModel::get($teacher_id);
return  $teacher->name; 
}

这个方法放哪里呢,因为在模板里面是循环输出klass的内容,

 {volist?id="Klass"?name="Klasses"}
 <tr>
 <td>{$i}</td>
 <td>{$Klass.id}</td>
 <td>{$Klass.name}</td>
 <td>{$Klass->getTeacher({$Klass.teacher_id})}</td>
 <td>
 <a
 type="button"
 class="btn?btn-warning"
 href="{:url('delete?id='.$Klass->getData('id'))}"
 >删除</a>
 <a
 type="button"
 class="btn?btn-info"
 href="{:url('edit?id='.$Klass->getData('id'))}"
 >编辑</a
 >
 </td>
 </tr>
 {/volist}
 </tbody>
 </table>
 {$Klasses->render()}

所以方法应该放在klass模型里面:

use appindexmodelTeacher as TeacherModel;
class Klass extends Model
{
 public function getTeacher($teacher_id)
 {
 $Klass = TeacherModel::get($teacher_id);
 return $Klass['name'];
 }
}

然后在模板内这样调用了:

{$Klass->getTeacher({$Klass.teacher_id})}

发现最后渲染的结果:
{$Klass->getTeacher(1)}
{$Klass->getTeacher(2)}
之类的。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

啊,我自己是。。。。
模板调用应该是这样的:

{$Klass->getTeacher($Klass.teacher_id)}

最里面的{}不需要了.....


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...