Isla
Isla

Reputation: 2462

How to display in Smarty3 part of template which is in a PHP variable?

I'm dealing with a task, which is partially done by someone else. So I have some texts in database and need to take them and add to existing templates. The problem is, texts include some variables, which I want to display (they are provided to template). Now I can see only curly brackets and name of variable inside, not its value.

PHP:

$var = "{$rest_name} offers good {$cuisine} food.";
$smarty->assign("rest_name", "My Rest");
$smarty->assign("cuisine", "thai");
$smarty->assign("desc", $var);

TPL:

{$desc}

Displays {$rest_name} offers good {$cuisine} food. but I want to see there My Rest offers good thai food..

I cannot do this in PHP as different parts of application deliver data, so only point where everything is known is a template.

How can I force Smarty to render PHP variable as a part of template?

Upvotes: 1

Views: 264

Answers (1)

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111829

The first thing you need to use single quotes in PHP for {$rest_name} offers good {$cuisine} food.. Otherwise you get warnings that variables are not defined, so correct code in PHP is:

$var = '{$rest_name} offers good {$cuisine} food.';
$smarty->assign("rest_name", "My Rest");
$smarty->assign("cuisine", "thai");
$smarty->assign("desc", $var);

In Smarty you can use:

{include file="string:$desc"}

it will display parsed string immediately.

You can assign it to variable using:

{include file="string:$desc" assign="assigned"}
some other stuff here
{$assigned}

In both case you will get your desired output:

My Rest offers good thai food.

Upvotes: 1

Related Questions