2

我的文件结构:

--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 模板?

4

1 回答 1

1

简短的回答,因为您需要从 testpage.php 上一个目录以到达包含 smarty 目录的目录,就像您对 header.php 包含所做的那样,您需要对 smarty 包含目录执行相同的操作。

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

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

例如在 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”子目录中的所有内容都被认为是“不安全的”,这让人思考关于什么是安全的,什么是不容易的。

于 2012-12-16T12:56:35.893 回答