Php functions in smarty template

Smarty Icon

You may use the Smarty logo according to the trademark notice. For sponsorship, advertising, news or other inquiries, contact us at:

Sites Using Smarty

Chapter 17. Advanced Features

Security

Security is good for situations when you have untrusted parties editing the templates eg via ftp, and you want to reduce the risk of system security compromises through the template language. The settings of the security policy are defined by properties of an instance of the Smarty_Security class. These are the possible settings:

  • $php_handling determines how Smarty to handle PHP code embedded in templates. Possible values are:
  • Smarty::PHP_PASSTHRU -> echo PHP tags as they are
  • Smarty::PHP_QUOTE -> escape tags as entities
  • Smarty::PHP_REMOVE -> remove php tags
  • Smarty::PHP_ALLOW -> execute php tags

The default value is Smarty::PHP_PASSTHRU.

If security is enabled the $php_handling setting of the Smarty object is not checked for security.

  • http://smarty.net/foo
  • http://smarty.net/foo
  • http://www.smarty.net/foo
  • http://smarty.net/foo
  • https://foo.bar.www.smarty.net/foo/bla?blubb=1

but deny access to these URIs:

  • http://smarty.com/foo (not matching top-level domain «com»)
  • ftp://www.smarty.net/foo (not matching protocol «ftp»)
  • http://www.smarty.net.otherdomain.com/foo (not matching end of domain «smarty.net»)

If security is enabled, no private methods, functions or properties of static classes or assigned objects can be accessed (beginningwith ‘_’) by the template.

To customize the security policy settings you can extend the Smarty_Security class or create an instance of it.

Example 17.1. Setting security policy by extending the Smarty_Security class

 $smarty = new Smarty(); // enable security $smarty->enableSecurity('My_Security_Policy'); ?>

Example 17.2. Setting security policy by instance of the Smarty_Security class

php_functions = null; // remove PHP tags $my_security_policy->php_handling = Smarty::PHP_REMOVE; // allow everthing as modifier $my_security_policy->$modifiers = array(); // enable security $smarty->enableSecurity($my_security_policy); ?>

Example 17.3. Enable security with the default settings

Note

Must security policy settings are only checked when the template gets compiled. For that reasion you should delete all cached and compiled template files when you change your security settings.

$php_modifier = array() ) will allow all PHP functions But in the examples it shows like: public $modifiers = array(); Which one is correct? BTW: when using it as an empty array (in both ways) I still couldn’t use strstr for example.

In examples 17.1 and 17.2 above, $modifiers should be $php_modifiers. [Moderator: please feel free to change the documentation and delete this comment. Thanks.]

Читайте также:  Justify self css не работает

Источник

Smarty Icon

You may use the Smarty logo according to the trademark notice. For sponsorship, advertising, news or other inquiries, contact us at:

Sites Using Smarty

is used to create functions within a template and call them just like a plugin function. Instead of writing a plugin that generates presentational content, keeping it in the template is often a more manageable choice. It also simplifies data traversal, such as deeply nested menus.

Note

  • The tag must have the name attribute which contains the the name of the template function. A tag with this name can be used to call the template function.
  • Default values for variables can be passed to the template function as attributes. Like in PHP function declarations you can only use scalar values as default. The default values can be overwritten when the template function is being called.
  • You can use all variables from the calling template inside the template function. Changes to variables or new created variables inside the template function have local scope and are not visible inside the calling template after the template function is executed.
Attribute Name Type Required Default Description
name string Yes n/a The name of the template function
[var . ] [var type] No n/a default variable value to pass local to the template function

Note

You can pass any number of parameter to the template function when it is called. The parameter variables must not be declared in the tag unless you what to use default values. Default values must be scalar and can not be variable. Variables must be passed when the template is called.

Example 7.43. Recursive menu example

[‘item3-1′,’item3-2′,’item3-3’ => [‘item3-3-1′,’item3-3-2′]],’item4’]>

Will generate the following output

* item1 * item2 * item3 o item3-1 o item3-2 o item3-3 + item3-3-1 + item3-3-2 * item4

Источник

Use php functions in Smarty template

Here you’re not deciding how to display, but generate data — usually what the model layer is supposed to do.

1 Answer 1

You haven’t explained what result you want to achieve and in fact you should rather do such things in controller/model than in view.

However if in PHP you have:

$smarty->assign( 'data', array( 'data' => array( array('a' => 'one', 'b' => 'two'), array('a' => 'three', 'b' => 'four') ) ) ); 

And in Smarty file you have:

array(4) < [0]=>string(3) "one" [1]=> string(3) "two" [2]=> string(5) "three" [3]=> string(4) "four" > 

array_push in this case is not the best solution because it will also display number of elements, so using:

Читайте также:  Почему media не работает css

you would also get numbers displayed:

1 2 3 4 array(4) < [0]=>string(3) "one" [1]=> string(3) "two" [2]=> string(5) "three" [3]=> string(4) "four" > 

EDITED ANSWER ACCORDING TO COMMENT

I want to display like this: a:b, c:d where this elements are| $array[0] = Array(‘aa’ => ‘a’, ‘bb’ => ‘b’) $array[1] = Array(‘cc’=>’c’, ‘dd’=>’d’);

$array = array(); $array[0] = Array('aa' => 'a', 'bb' => 'b'); $array[1] = Array('cc'=>'c', 'dd'=>'d'); $smarty->assign( 'data', $array ); 

But it’s not connected to the question in anyway where you asked about using PHP function array_push in Smarty template

I want to display like this: a:b, c:d where this elements are| $array[0] = Array(‘aa’ => ‘a’, ‘bb’ => ‘b’) $array[1] = Array(‘cc’=>’c’, ‘dd’=>’d’);

@OsomA What do you mean? You told that you want to put data into array. And var_dump function displays data only in its format. If you wanted simple display data why you wanted to use array_push ? I don’t get it. You should edit your question and explain what you want to achieve, put there original PHP data (in var_export and not var_dump format)

Источник

Smarty: how to use PHP functions?

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

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.

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:

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

Call a function, passing a single parameter:

 // same as: strtoupper("this is my string") // same as: strtoupper($a) 

Call a function, passing multiple parameters

 // same as: str_replace("/", "-", "this is my string") // same as: str_replace("/", "-", $a) 

Or you can use this: (call function directly)

Further more you can not only call that way a native php functions but also functions you declared in your php code without registering it as plugin (tested for Smarty 3).

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.

Читайте также:  Social sharing button html

So, is it impossible to do in Smarty? I’m re-purposing the data and don’t think I should be passing it as a separate variable. In one scenario, I do need the HTML tags of $a; in another scenario, I don’t.

I won’t tell you if it’s possible or not (it’s been some time since I worked with Smarty). My point is, it is not something you should do.

Joshua Burns: usually for developers’ confort. If not that, we’d still be doing all our coding in assembly.

@Mchl I think It’s debatable. strtoupper for instance I think is nice to have in the view as the data is still the same, just presented in upper case.

Uppercasing a string and stripping html tags are quite different operations. While I can agree the former is well within the realm of data presentation, the latter imho is not.

Источник

Документация Smarty

Все атрибуты, передаваемые в функции шаблона из самого шаблона, хранятся в $params в виде ассоциативного массива. Получить доступ к его значениям можно напрямую: $params[‘start’] или используя extract($params) для импорта в таблицу.

Вывод (возвращаемое значение) функции будет подставлен в место расположения тэга функции в шаблоне (функция fetch() например). В качестве альтернативы, функция может выполнять какие либо действия без какого-либо вывода ( assign() функция).

Если функция должна присвоить(assign) значения некоторым переменным в шаблоне или использовать иные возможности Smarty, то можно работать с объектом $smarty как обычно.

Пример 16-1. Функция-плагин с выводом

/*
* Smarty plugin
* ————————————————————-
* File: function.eightball.php
* Type: function
* Name: eightball
* Purpose: outputs a random magic answer
* ————————————————————-
*/
function smarty_function_eightball ( $params , & amp ; $smarty )
$answers = array( ‘Да’ ,
‘Нет’ ,
‘Никоим образом’ ,
‘Перспектива так себе. ‘ ,
‘Спросите позже’ ,
‘Все может быть’ );

$result = array_rand ( $answers );
return $answers [ $result ];
>
?>

которая может быть использована в шаблоне следующим образом:

Вопрос: Мы когда-нибудь найдем время для отпуска? Ответ: .

Пример 16-2. Функция-плагин без вывода

/*
* Smarty plugin
* ————————————————————-
* File: function.assign.php
* Type: function
* Name: assign
* Purpose: assign a value to a template variable
* ————————————————————-
*/
function smarty_function_assign ( $params , & amp ; $smarty )
extract ( $params );

if (empty( $var )) $smarty -> trigger_error ( «assign: missing ‘var’ parameter» );
return;
>

if (! in_array ( ‘value’ , array_keys ( $params ))) $smarty -> trigger_error ( «assign: missing ‘value’ parameter» );
return;
>

$smarty -> assign ( $var , $value );
>
?>

Источник

Оцените статью