在smarty模板文件中包含PHP文件

тнє*_*ufi 3 php smarty include whmcs

我完全不了解smarty模板系统。我想做的是包括一个php文件,以在.tpl文件(这是WHMCS模板)中获取一些变量。

我试过像:

{php} include ('file.php'); {/php} //doesn't work

{include_php file='file.php'}  //doesn't work
Run Code Online (Sandbox Code Playgroud)

我也遵循了这个问题的答案。仍然无法正常工作。

如何将其包含code.phpheader.tplWHMCS中?有什么帮助吗?

仅供参考:tpl和php文件都在同一目录中,如果仍然有帮助的话。

Mar*_*łek 5

确实不建议在Smarty中使用php代码。实际上,它现在已被弃用,您应该尽可能避免这种解决方案,因为它通常没有意义。

但是,如果出于某些原因确实要在Smarty文件中使用PHP,则需要使用SmartyBC(Smarty向后兼容)类而不是Smarty类。

因此,例如,代替:

require_once(_PS_SMARTY_DIR_.'Smarty.class.php');
$smarty = new Smarty();
Run Code Online (Sandbox Code Playgroud)

您应该使用:

require_once('SmartyBC.class.php');
$smarty = new SmartyBC();
Run Code Online (Sandbox Code Playgroud)

然后,您将可以在Smarty模板文件中使用PHP

编辑

如果您只是想包含它,可能是您的目录问题(但是您没有显示任何错误)。

我假设您将文件保存在模板目录中,并使用以下命令正确设置了文件:

$smarty->setTemplateDir('templates');
Run Code Online (Sandbox Code Playgroud)

如果您在Smarty中简单地显示index.tpl文件,并且此PHP文件在同一目录中(在template目录中),则可以不带路径就包括它。

但是,如果您在此index.tpl文件中包含另一个tpl文件,则要包含php文件时,您需要将完整路径传递给该PHP文件,例如:

{include_php 'templates/file.php''}
Run Code Online (Sandbox Code Playgroud)


Gla*_*den 5

您以错误的方式使用 Smarty。Smarty 的重点是不在您的演示文稿中包含任何 PHP(视图,也就是好的 ol' HTML)。

所以,无论你想在那个 PHP 文件中做什么,让它发挥它的魔力,但将实际结果发送给 Smarty。例如,您想显示从数据库中获取的用户表吗?执行查询,获取结果并将结果(如结果数组)传递给 smarty,如下所示:

<?php
$smarty = new Smarty();
$users = $db->query('SELECT * FROM users');

// Assign query results to template file.
$smarty->assign('users', $users);

// Compile and display the template.
$smarty->display('header.tpl');
Run Code Online (Sandbox Code Playgroud)

现在,在您的 smarty 模板中,您可以像这样访问该数组:

<html>
    {foreach from=$users item=user}
        Username: {$user->username}<br />
    {/foreach}
</html>
Run Code Online (Sandbox Code Playgroud)

我希望你明白我要去哪里。将您的应用程序逻辑保留在 PHP 文件中,让模板只负责外观。保持模板尽可能愚蠢!