Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Smarty: how to use PHP functions?

Tags:

php

smarty

Say I have the following in my TPL file:

{$a}

and I want to apply certain PHP native functions (e.g. strip_tags) to that Smarty variable. Is this possible within the TPL? If so, how?

like image 559
StackOverflowNewbie Avatar asked Jan 21 '11 00:01

StackOverflowNewbie


4 Answers

You can use any php function in a smarty template in the following way:

{$a|php_function_name}

or

{$a|php_function_name:param2:param3:...}

In the second example you can specify additional parameters for the php function (the first is always $a in our case).

for example: {$a|substr:4:3} should result something like substr($_tpl_vars['a'],4,3); when smarty compiles it.

like image 55
Zsolti Avatar answered Sep 23 '22 15:09

Zsolti


The best way is probably to create your own plugins and modifiers for Smarty. For your specific example, Smarty already has a strip_tags modifier. Use it like this:

{$a|strip_tags}
like image 27
Sander Marechal Avatar answered Sep 23 '22 15:09

Sander Marechal


Or you can use this: (call function directly)

{rand()}
like image 29
B. Altan Kocaoglu Avatar answered Sep 21 '22 15:09

B. Altan Kocaoglu


Very good question, it took me a while to completely figure this one out.

Call a function, passing a single parameter:

{"this is my string"|strtoupper}
// same as:
strtoupper("this is my string")

{$a:strtoupper}
// same as:
strtoupper($a)

Call a function, passing multiple parameters

{"/"|str_replace:"-":"this is my string"}
// same as:
str_replace("/", "-", "this is my string")

{"/"|str_replace:"-":$a}
// same as:
str_replace("/", "-", $a)
like image 29
Joshua Burns Avatar answered Sep 21 '22 15:09

Joshua Burns