2012-12-16 44 views
2

我的文件结构:访问Smarty的模板

--header.php 
--smarty 
    --templates 
    -- x.tpl 
    --cache 
    --configs 
    --templates_c 
--articles 
    -- testPage.php 

代码中的header.php

$smarty = new Smarty(); 

$smarty->setTemplateDir('smarty/templates'); 
$smarty->setCompileDir('smarty/templates_c'); 
$smarty->setCacheDir('smarty/cache'); 
$smarty->setConfigDir('smarty/configs'); 

守则testPage.php

<?php 
    include('../header.php'); 
    $smarty->display('x.tpl'); 
?> 

我打这个错误:

PHP Fatal error: Uncaught exception 'SmartyException' with message 'Unable to 
load template file 'x.tpl'' in 
/usr/local/lib/php/Smarty/sysplugins/smarty_internal_templatebase.php:127 

如何设置正确的路径来访问我的testPage.php中的smarty模板?

+1

你有没有试过提供绝对路径? – shawndreck

+0

你有没有解决他的问题? – Ted

回答

1

简短的回答,因为你需要从你的testpage.php上去一个目录,以到达包含你的smarty目录的目录,就像你为header.php所做的那样,包括你需要为聪明的包含目录。

$smarty->setTemplateDir('../smarty/templates'); 

这样做很好的一种方法是定义如何到达项目的根目录,然后在include中使用它。

例如在testPage.php

define("PATH_TO_ROOT", "../"); 

,然后在header.php中

$smarty->setTemplateDir(PATH_TO_ROOT.'smarty/templates'); 
$smarty->setCompileDir(PATH_TO_ROOT.'smarty/templates_c'); 
$smarty->setCacheDir(PATH_TO_ROOT.'smarty/cache'); 
$smarty->setConfigDir(PATH_TO_ROOT.'smarty/configs'); 

这使得那是微不足道的设置从另一个PHP文件可能是在其他位置的Smarty的目录。例如在一个名为“tests/webtests/frontend”的目录中,您可以将PATH_TO_ROOT定义为“../../../”,并且对设置Smarty的调用仍然有效。

你也可以让header.php检查PATH_TO_ROOT是否被定义,以防止被直接调用。作为一个方面说明,你可能想考虑在Smarty目录下没有templates_c和cache目录,而是在其他地方创建一个单独的目录来写入生成的数据(因此可能容易受到注入攻击)。对于我的项目,我有一个位于项目根目录下的'var'目录,该目录包含日志文件,缓存,生成模板等的所有目录。'var'子目录中的所有内容都被认为是'unsafe',这使得思考关于什么是安全的,什么是不容易的。

+0

不,因为如果header.php包含在树目录中不同深度的几个php文件中,../smarty路径链接到不存在的目录。 – Aubin

+0

嗨,奥宾,你误解了。正在运行的文件是testPage.php,因此所有目录路径都与该文件所在的目录相关,而不是相对于header.php – Danack

+0

PATH_TO_ROOT并不总是“../” – Aubin