StackOverflowNewbie
StackOverflowNewbie

Reputation: 40653

Smarty: how to use PHP functions?

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?

Upvotes: 8

Views: 34028

Answers (6)

B. Altan Kocaoglu
B. Altan Kocaoglu

Reputation: 393

Or you can use this: (call function directly)

{rand()}

Upvotes: 9

Zsolti
Zsolti

Reputation: 1607

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.

Upvotes: 24

Joshua Burns
Joshua Burns

Reputation: 8582

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)

Upvotes: 7

RobertPitt
RobertPitt

Reputation: 57268

Smarty already has a Language Modifier built in for this.

{$a|strip_tags}

You don't need Native functions as there already integrated into the plugin system

http://www.smarty.net/docsv2/en/language.modifier.strip.tags.tpl

others here:

http://www.smarty.net/docsv2/en/language.modifiers.tpl

Upvotes: 0

Sander Marechal
Sander Marechal

Reputation: 23216

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}

Upvotes: 8

Mchl
Mchl

Reputation: 62395

The whole point of templating systems is to abstract the creation of views from the underlying language. In other words, your variables should be prepared for displaying before they are passed to a templating engine, and you should not use any PHP functions in the template itself.

Upvotes: 0

Related Questions