Rajat
Rajat

Reputation: 34158

Access Smarty Template

My file structure:

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

Code in header.php

$smarty = new Smarty();

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

Code in testPage.php

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

I am hitting this error:

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

How to set the correct path to access the smarty template in my testPage.php?

Upvotes: 2

Views: 2658

Answers (1)

Danack
Danack

Reputation: 25721

Short answer, as you need to go up one directory from your testpage.php to get to the directory that contains your smarty directory, like you've done for the header.php include you need to do the same for the smarty include directories.

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

One way of doing this nicely is defining how to get to the root directory of your project and then using that in the include.

e.g. in testPage.php

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

and then in 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');

This makes it then be trivial to setup the Smarty directories from another PHP file that may be in another location. e.g. in a directory called "tests/webtests/frontend" you could define the PATH_TO_ROOT as "../../../" and the calls to setup Smarty would still work.

You could also make header.php check that PATH_TO_ROOT is defined, to prevent it from being called directly.

As a side note, you might want to consider not having the templates_c and cache directory under the Smarty directory, but instead create a separate directory elsewhere to write data that is generated (and so potentially vulnerable to injection attack). For my projects I have a 'var' directory located off the projects root directory, which holds all the directories for log files, caches, generated templates etc. Everything in the sub-directory from 'var' is considered 'unsafe' which makes thinking about what is safe and what isn't much easier.

Upvotes: 1

Related Questions