Reputation: 147
I just started to write PHP code and HTML and i have a problem. I have a function which create HTML code like this:
function test(){
echo "<div style=\"font-size:13px;font-family:Arial\">";
echo "<a href='google.com'>sasa</a>";
echo "</div>";
}
When i call $a = $this->test() i don't want to render the html, just to send to smarty. I already tried with json encode but it is not working. Please help me.
Upvotes: 0
Views: 376
Reputation: 111829
If you use Smarty you shouldn't do such thing at all. What's the point of using Smarty and putting HTML code into PHP? There is none.
You should use fetch()
instead
You can do:
function test($smarty){
return $smarty->fetch('testtemplate.tpl');
}
$smarty->assign('mycode', test($smarty));
And in testtemplate.tpl
you can simply put:
<div style="font-size:13px;font-family:Arial">
<a href='google.com'>sasa</a>
</div>
In Smarty you have 2 methods:
display()
- for displaying template
fetch()
- to fetch template into string and then do anything you want with it
Upvotes: 1
Reputation: 46900
Replace your echo
s with a single return
and you can send the function's return value to smarty or use it anywhere else.
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
You can also use the Heredoc syntax for HTML strings
$content= <<<HTML
<div style="font-size:13px;font-family:Arial">
<a href='google.com'>sasa</a>
</div>
HTML;
Upvotes: 2
Reputation: 116
Modify your function according to this -
function test(){
return "<div style='font-size:13px;font-family:Aria;'>
<a href='google.com'>sasa</a></div>";
}
and Use - $a = $this->test()
Upvotes: 0
Reputation: 2610
Have it return a value instead of displaying its output;
function test(){
$out = "<div style=\"font-size:13px;font-family:Arial\">";
$out .= "<a href='google.com'>sasa</a>";
$out .= "</div>";
return $out;
}
Upvotes: 0
Reputation: 7034
Although I don't like Smarty in the modern era, it seems it's still used. The basic idea behind it is that it recieves it metadata by assignation from PHP. So if you want to send something to smarty, use assign. No matter it's HTML or not. Just don't echo it, but instead - return it
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());
Upvotes: 1
Reputation: 65
You need to create a variable to contain the HTML code and have your function return it. Below is an example:
function test() {
$ret = "<div style=\"font-size:13px;font-family:Arial\">";
$ret .= "<a href='google.com'>sasa</a>";
$ret .= "</div>";
return $ret;
}
The $ret .= 'string'
will append the given string to your variable instead of assigning it.
Upvotes: 0