How to add PHP code to .tpl file [duplicate]

2020-02-12 07:42发布

I need to display some external data from php file to .tpl file. For this I want to include php file to .tpl file. I have tried folllowing code to display php file content to tpl.

{php} include('custom_code.php'); {/php}

but on page output was include('custom_code.php');

标签: php smarty
3条回答
走好不送
2楼-- · 2020-02-12 08:30

There is a best practise guide on smarty homepage. #1 is Do not embed PHP!

http://www.smarty.net/best_practices

Try this: {include_php file="/path/to/somefile.php"}

But notice:

{include_php} is deprecated from Smarty, use registered plugins 
to properly insulate presentation from the application code. 
As of Smarty 3.1 the {include_php} tags are only available 
from SmartyBC.

So best way is to write a smarty plugin as explained by rodneyrehm

查看更多
Melony?
3楼-- · 2020-02-12 08:34

You shouldn't add PHP code to the template. It will make whole idea of templates spoiled.

You have to add PHP code to controller, not template.

查看更多
狗以群分
4楼-- · 2020-02-12 08:35

{php} has been deprecated. Have a look at Extending Smarty With Plugins.

put the follwing in …/plugins/function.yourplugin.php:

<?php
function smarty_function_yourplugin(array $params, Smarty_Template_Instance) {
    include 'your_other_file.php';
}

and use in your template:

{yourplugin}
查看更多
登录 后发表回答