【问题标题】:Assign Smarty variable to PHP with Smarty 3使用 Smarty 3 将 Smarty 变量分配给 PHP
【发布时间】:2015-10-09 21:02:51
【问题描述】:

我使用的商店系统从 smarty 2 更新到 smarty 3,这导致了我们网站上的一系列问题。最糟糕的是,我们分配给 PHP 中使用它们的所有 Smarty 变量都不再起作用了。

一个简短的例子:

{assign var=test value=$ORDER_NUMBER}
{php}
    $order = $this->get_template_vars('test');
    echo $order;   
{/php}

这会导致以下错误:

FATAL ERROR(1): "Using $this when not in object context"

现在在 Smarty 页面上,我发现了一些代码行,它们的作用相同但看起来有点不同,例如这个:

$order = $smarty->getTemplateVars('test');

导致:

FATAL ERROR(1): "Call to a member function getTemplateVars() on null"

自 Smarty 3 以来,我发现所有这些“解决方案”都没有工作了。

【问题讨论】:

  • get_template_vars() is deprecated use getTemplateVars() and make sure before this line: $smarty->getTemplateVars('test')that you have initialized your smarty object.
  • php-tag 在 smarty3 中也已弃用,您应该使用可用的可能性来扩展 smarty 以使用自定义块/功能/...替换您对 php-blocks 的使用...跨度>
  • 您的第二种方法应该使用 $smarty 变量。如果没有,也许尝试把 global $smarty;在你的代码之前。但是,您的代码很糟糕而且非常过时,需要随着时间的推移进行更改。在 smarty 的下一个版本中,它可能根本无法工作。

标签: php smarty smarty3


【解决方案1】:

无论出于何种原因,上述方法均无效。我现在将 {PHP} 标记中的代码外包给外部 PHP 文件,然后将函数返回给 smarty。

下面我有一个例子供任何人使用它(不要忘记将你的 PHP 文件包含到你的 index.php 或其他文件中):

我想从数据库中获取有关产品的一些信息,但 smarty 中只给出了{$module_data.PRODUCTS_ID}

所以在我使用 smarty 标记的文件中,我将此变量发送到我在 PHP 中的函数:{$module_data.PRODUCTS_ID|@get_random_function}

然后在我的外部 PHP 文件中执行我的 PHP 函数并返回我需要的数据:

function get_random_function($products_id)
{
    $t_sql = $sql = "SELECT * FROM products WHERE products_id='".$products_id."'";
    $retval = mysql_query($t_sql);
    $row = mysql_fetch_assoc($retval);


    return $row['gm_needed_data'];
}

现在{$module_data.PRODUCTS_ID|@get_random_function} 输出我的 PHP 函数的返回值。

【讨论】:

    猜你喜欢
    • 2015-03-20
    • 2012-05-03
    • 1970-01-01
    • 1970-01-01
    • 2013-07-01
    • 2013-04-17
    • 2011-07-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多