Home >Backend Development >PHP Tutorial >smarty custom function usage examples, smarty custom examples_PHP tutorial
The examples in this article describe the usage of smarty custom functions. Share it with everyone for your reference, the details are as follows:
<?php require_once "smarty.config.php"; //自定义一个函数 //调用方法:<{test1 times="4" size="5" con="Hello,Liuyibao!" color="red"}> function test1($args){ $str=""; for($i=0;$i<$args['times'];$i++){ $str.="<p style='font-size:{$args['size']}em;color:{$args['color']}'>{$args['con']}</p>"; } return $str; } //自定义一个块方式函数 //调用方法<{test1}><{/test1}> function test2($args,$con){ $str=""; for($i=0;$i<$args['times'];$i++){ $str.="<p style='font-size:{$args['size']}em;color:{$args['color']}'>{$con}</p>"; } return $str; } //定义一个计算方法 function jisuan($args){ switch($args['operate']){ case "+" :$res=$args['num1']-$args['num2'];break; case "-" :$res=$args['num1']-$args['$num2'];break; case "*" :$res=$args['num1']*$args['$num2'];break; case "/" :$res=$args['num1']/$args['$num2'];break; } return $res; } //注册一下 $smarty->register_function("liuyibao","test1"); //注册块函数 $smarty->register_block("liuyibao2","test2"); //注册函数jisuan $smarty->register_function("jisuan","jisuan"); //替换变量 $smarty->display("function.tpl"); ?>
PS: Here are several formatting/beautifying/conversion tools recommended on this site to help you sort out the messy code. I believe everyone can use it in future development:
php code online formatting and beautification tool:
http://tools.jb51.net/code/phpformat
JavaScript code beautification/compression/formatting/encryption tool:
http://tools.jb51.net/code/jscompress
Online XML formatting/compression tool:
http://tools.jb51.net/code/xmlformat
JSON code formatting and beautification tool:
http://tools.jb51.net/code/json
Online XML/JSON conversion tool:
http://tools.jb51.net/code/xmljson
JSON code online formatting/beautifying/compressing/editing/conversion tool:
http://tools.jb51.net/code/jsoncodeformat
SQL code online formatting and beautification tool:
http://tools.jb51.net/code/sqlcodeformat
Readers who are interested in more Smarty-related content can check out the special topics on this site: "Basic Tutorial for Getting Started with Smarty Templates", "Summary of PHP Template Technology", "Summary of PHP Database Operation Skills Based on PDO", "PHP Operations and Operators" Usage summary", "PHP network programming skills summary", "PHP basic syntax introductory tutorial", "php object-oriented programming introductory tutorial", "php string (string) usage summary", "php mysql database operation introductory tutorial" and "Summary of Common Database Operation Skills in PHP"
I hope this article will be helpful to everyone’s PHP program design based on smarty templates.