使用html代码调用PHP函数并将其发送给Smarty

时间:2014-07-23 08:11:39

标签: php html smarty

我刚刚开始编写PHP代码和HTML,我遇到了问题。我有一个创建HTML代码的函数:

function test(){
echo "<div style=\"font-size:13px;font-family:Arial\">";
    echo "<a href='google.com'>sasa</a>";
echo "</div>";
}

当我拨打$ a = $ this-&gt; test()时,我不想渲染html,只是为了发送给smarty。我已经尝试过使用json编码,但它无法正常工作。请帮帮我。

6 个答案:

答案 0 :(得分:2)

echo替换为单个return,您可以将该功能的返回值发送给smarty或在其他地方使用。

function test(){
 $content= "<div style=\"font-size:13px;font-family:Arial\">";
 $content.= "<a href='google.com'>sasa</a>";
 $content.=  "</div>";
 return $content;
}

$a = $this->test();    // $a has your unrendered html

您还可以对HTML字符串使用 Heredoc 语法

$content=  <<<HTML
 <div style="font-size:13px;font-family:Arial">
 <a href='google.com'>sasa</a>
 </div>
HTML;

答案 1 :(得分:1)

虽然我不喜欢现代时代的Smarty,但它似乎仍在使用。它背后的基本思想是它通过PHP的赋值来接收它的元数据。所以如果你想发送一些东西给smarty,请使用assign。不管它是不是HTML。只是不回应它,而是 - 返回它

function test(){
    $html = "<div style=\"font-size:13px;font-family:Arial\">";
    $html .= "<a href='google.com'>sasa</a>";
    $html .= "</div>";
    return $html;
}

$smarty->assign('myVar', test());

答案 2 :(得分:1)

如果你使用Smarty,你根本不应该这样做。使用Smarty并将HTML代码放入PHP有什么意义?没有。

您应该使用fetch()代替

你可以这样做:

function test($smarty){
   return $smarty->fetch('testtemplate.tpl'); 
}
$smarty->assign('mycode', test($smarty));

testtemplate.tpl中你可以简单地说:

<div style="font-size:13px;font-family:Arial">
    <a href='google.com'>sasa</a>
</div>

在Smarty中你有两种方法:

display() - 用于显示模板

fetch() - 将模板提取到字符串中然后随意做任何事情

答案 3 :(得分:0)

您需要创建一个变量来包含HTML代码并让您的函数返回它。以下是一个例子:

function test() {
    $ret  = "<div style=\"font-size:13px;font-family:Arial\">";
    $ret .= "<a href='google.com'>sasa</a>";
    $ret .= "</div>";
    return $ret;
}

$ret .= 'string'会将给定字符串附加到您的变量而不是分配它。

答案 4 :(得分:0)

让它返回值而不是显示其输出;

    function test(){
    $out = "<div style=\"font-size:13px;font-family:Arial\">";
    $out .= "<a href='google.com'>sasa</a>";
    $out .= "</div>";
    return $out;
    }

答案 5 :(得分:0)

根据此修改您的功能 -

function test(){
    return "<div style='font-size:13px;font-family:Aria;'>
                   <a href='google.com'>sasa</a></div>";

}

并使用 - $ a = $ this-&gt; test()

相关问题