【问题标题】:Smarty: setting directoriesSmarty:设置目录
【发布时间】:2012-08-14 02:22:58
【问题描述】:

我对此不太确定,但是从 smarty 指令 http://www.smarty.net/docs/en/installing.smarty.basic.tpl 中阅读,每次我有一个新的 PHP 脚本时,我都必须设置 $template_dir、$compile_dir、$config_dir 和 $cache_dir。换句话说,我必须为每个 PHP 脚本添加以下代码行:

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

正确吗?你们有没有采取任何“捷径”来避免这种情况?

【问题讨论】:

  • 我的回答有意义吗,@jay kk?

标签: php templates smarty


【解决方案1】:

您应该在一个通用配置文件中设置所有这些内容,然后在需要时将其包含在内。

include( 'path/to/common_config.php' );

然后,在您的 common_config.php 中,您可以执行以下操作:

//set up Smarty
require_once( dirname( __FILE__ ) . '/smarty/Smarty.class.php' );
$smarty = new Smarty;
$smarty->error_reporting = E_ALL & ~E_NOTICE;
$smarty->setTemplateDir( dirname( __FILE__ ) . '/../templates' );
$smarty->setCompileDir( dirname( __FILE__ ) . '/../smarty/templates_c' );

使用“dirname(FILE)”将确保路径始终相对于通用配置文件。

现在您需要做的就是使用带有模板文件名称的显示方法:

$smarty->display( 'index.tpl' );

【讨论】:

  • 谢谢马修!我考虑过这种设置,但我认为如果 php 脚本位于不同的路径中,它可能会给我带来问题。例如:www/index.php -> template/index.tpl, www/subdirectory/somefile.php -> template/subdirectory/somefile.tpl 如何解决配置文件“common_config.php”中的问题?
  • 如果您将所有模板文件保存在同一目录中,则可以轻松访问它们。同样,只需在每个脚本中使用正确路径的 include(),模板就可以正常工作。 :)
【解决方案2】:

我认为更好的解决方案是扩展 Smarty 类。

<?php
require_once SMARTY_DIR . 'Smarty.class.php';

class Application extends Smarty {

    public function __construct() {
        parent::__construct();

        $this
            ->addTemplateDir (TPL_DIR)
            ->setCompileDir  (COMPILE_DIR)
            ->setConfigDir   (CONFIG_DIR)
            ->setCacheDir    (CACHE_DIR)
            ->setPluginsDir  ( array ( SMARTY_DIR.'plugins', PRESENTATION_DIR.'smarty_plugins' ) );

        $this->caching = false;       // set Smarty caching off by default
        $this->muteExpectedErrors();  // can't remember what this does exactly, but it tunes down the sensitivity of errors
        $this->debugging = SMARTY_DEBUG; // setting controlled in config. file
    }
}
?>

然后简单地启动新的“应用程序”类。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-29
    • 1970-01-01
    • 2019-12-21
    • 2013-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多