I want to call a php method in my smarty template.
I have the class
class TestClass
{
public static myMth($vars) {
var_dump($vars);
}
}
In my template i put:
{TestClass::myMth($someVar)}
That doesn't work. I have the error:
Parse error: syntax error, unexpected 'myMth' (T_STRING), expecting variable (T_VARIABLE)
Is there something wrong in my code ?
In fact it works without a problem (Smarty 3.1.19):
In PHP:
$data['elements'] = [1,2,3,4,5,6,7,8,9,10,11];
$smarty->assign('someVar',$data);
class TestClass
{
public static function myMth($vars) { // added function word here - you missed it in question
var_dump($vars);
echo "<br />test test test<br />";
}
}
In Smarty:
{TestClass::myMth($someVar)}
Output:
array(1) { ["elements"]=> array(11) { [0]=> int(1) [1]=> int(2) [2]=> int(3) [3]=> int(4) [4]=> int(5) [5]=> int(6) [6]=> int(7) [7]=> int(8) [8]=> int(9) [9]=> int(10) [10]=> int(11) } }
test test test
However I don't think it's the best way of using Smarty.
You should rather use:
$smarty->assign('result', TestClass::myMth($data));
Why? It's quite simple. Smarty is Template engine and you should only display data here. You should not launch classes/method and so on. What if myMyth function name will change or arguments will change? You will need to change your Smarty template files. Better is to assign to Smarty only output of this method.
However if you still want to do that you can also look at Static classes section at Smarty website.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With