Php Smarty模板引擎-添加动态扩展块
[很抱歉我的英语不好] 我试图让我的php动态添加到我的模板中,以调用母版页块。下面是我当前演示的模板代码和母版页 ------------default.tpl------------------Php Smarty模板引擎-添加动态扩展块,php,smarty,Php,Smarty,[很抱歉我的英语不好] 我试图让我的php动态添加到我的模板中,以调用母版页块。下面是我当前演示的模板代码和母版页 ------------default.tpl------------------ <!-- default.tpl --> <!doctype html> <html lang="pt-br"> <head> <meta charset="UTF-8" /> <title>Project<
<!-- default.tpl -->
<!doctype html>
<html lang="pt-br">
<head>
<meta charset="UTF-8" />
<title>Project</title>
</head>
<body>
<div class="container">
{block name="content"}{/block}
</div>
{block name="javascript"}{/block}
</body>
{extends file="default.tpl"}
{block name="content"}
Hello World
{/block}
$this->smarty->extends('default.tpl'); //I don't know if is possible do something like this
$this->smarty->blocks('javascript',array('//cdn.jquery.com')); //I don't know if is possible do something like this too
$this->smarty->display('index');
--------------index.php------------------
<!-- default.tpl -->
<!doctype html>
<html lang="pt-br">
<head>
<meta charset="UTF-8" />
<title>Project</title>
</head>
<body>
<div class="container">
{block name="content"}{/block}
</div>
{block name="javascript"}{/block}
</body>
{extends file="default.tpl"}
{block name="content"}
Hello World
{/block}
$this->smarty->extends('default.tpl'); //I don't know if is possible do something like this
$this->smarty->blocks('javascript',array('//cdn.jquery.com')); //I don't know if is possible do something like this too
$this->smarty->display('index');
Smarty的工作方式与您描述的几乎相同,但语法有点不同。以下是您需要如何编写它: default.tpl(片段) index.php
$this->smarty->assign('javascript', array('//cdn.jquery.com'));
$this->smarty->display('index.tpl');
这就是Smarty的工作原理。有关更多信息,请阅读。第3-13节解释了基本用法
更新:此解决方案提供了Smarty 2的工作方式。此外,该链接指向Smarty 2的文档。我不知道Smarty 3中实现的所有新功能。但是,这里介绍的方法在Smarty 3中也适用(我从2010年开始使用Smarty 3,但从未觉得需要Smarty 2中没有的功能)。两个模板文件看起来都不错。PHP文件中存在问题:
$this->smarty->extends('default.tpl'); //I don't know if is possible do something like this
没有名为extends()
的方法。在模板中使用模板函数{extend}
$this->smarty->blocks('javascript',array('//cdn.jquery.com')); //I don't know if is possible do something like this too
没有名为block()
或blocks()的方法。您可以在子模板(index.tpl
)中定义块的内容,方法与在content
中所做的相同,或者将数据分配给模板变量并在模板中显示。标量变量可以使用语法{$variable}
显示,而数组可以使用{foreach}
内置函数进行迭代
$this->smarty->display('index');
这也不起作用,因为模板的名称是'index.tpl'
,而不仅仅是'index'
。Smarty不会自行附加终止。它只是尝试使用您提供的名称查找文件
我通过添加
error_reporting(E_ALL);
ini_set('display_errors', '1');
在你的脚本之上不要阻止PHP在开发计算机上显示错误。仅在生产服务器上执行此操作感谢您的快速回复。。。我也知道如果可以在php上定义include文件,不仅可以在index.tplYou中使用{include file=$filename}
,还可以从php($smarty->assign('filename','some template.tpl');
)甚至使用assign
:{assign var=filename value='abc.tpl'}
。在内部,{assign}
只是一个执行上述$smarty->assign()的插件
适合您。当然,出于性能原因,最好尽可能多地从PHP代码中进行处理,让模板只在列表中运行、格式化和显示值。哦,我对Smarty的了解似乎已经过时了。Smarty 3具有功能和功能。我只是好久没有阅读文档了。很抱歉误导您但是,我在这个解决方案中提出的旧方法(Smarty 2)仍然有效,我在日常工作中使用它。对不起,$Smarty->display('index')是我自己的函数,在“index.tpl”中调用