2011-07-08 172 views
3

我试过{include_php file="phpfile.php"}{php}标签,但都导致不推荐的错误。你不能在Smarty中做到这一点吗?我无法在文档中找到任何内容。Smarty:如何在模板中包含php?

+5

您应该避免在模板中包含PHP。 – ThiefMaster

+0

那么我该如何做到这一点。我只是需要PHP逻辑以某种方式 –

+2

在您的PHP文件中执行它,并将其分配为模板var。 – ThiefMaster

回答

2

我绕过了这个问题。它创建具有该功能名为block.php_code.php插件文件:

function smarty_block_php_code($params, $content, &$smarty) 
{ 
    if (is_null($content)) 
    { 
     return; 
    } 
    if ('<?php' == substr($content,0,5) && '?>' == substr($content, -2)) 
     $content = substr($content,5,-2); 
    ob_start(); 
    eval($content); 
    return ob_get_clean(); 
} 

在您的模板,然后你可以写:

{php_code}{literal}<?php 

    print "Hello, world!"; 

?>{/literal}{/php_code} 
+1

尤达风格是丑陋的。特别是在没有*任何*优势 – ThiefMaster

+0

的情况下,您认为哪里有优势? – wonk0

+1

@ wonk0 [这将是一个优点。](http://stackoverflow.com/questions/4624536/which-one-will-execute-faster-if-flag-0-or-if-0-flag/4624562# 4624562) –

2

他们正在贬值是有原因的,因为他们允许他们的不良做法。 Smarty建议将包含的脚本放入PHP逻辑或创建一个plugin(这很简单)。

{php}标签已从Smarty中弃用,不应使用。改为将PHP逻辑放入PHP脚本或插件函数中。

Source

{include_php}从Smarty的过时,登记使用的插件来正确地从应用程序代码绝缘介绍。

Source

如果您有什么你想在你的phpfile.php做,我们可以帮你写一个插件功能。